Skip to main content
Back to problems
#2567
Medium Algorithms

Minimum score by changing two elements

Array Greedy Sorting
49.8% acceptance
Feb 25, 2026
272
270
You are given an integer array nums. The low score of nums is the minimum absolute difference between any two integers. The high score of nums is the maximum absolute difference between any two integers. The score of nums is the sum of the high and low scores. Return the minimum score after changing two elements of nums.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimize_sum(mut nums: Vec<i32>) -> i32 {
    nums.sort_unstable();
    let n = nums.len();
    // After changing 2 elements optimally:
    // - Low score = 0 (we can always make two elements equal)
    // - High score = max - min of remaining elements after removing 2 extremes
    // Options: remove 2 from left, 2 from right, 1 from each end
    let opt1 = nums[n - 1] - nums[2]; // remove 2 smallest
    let opt2 = nums[n - 3] - nums[0]; // remove 2 largest
    let opt3 = nums[n - 2] - nums[1]; // remove 1 smallest + 1 largest
    opt1.min(opt2).min(opt3)
  }
}