[LeetCode] Minimum Score by Changing Two Elements

2567. Minimum Score by Changing Two Elements

You are given a 0-indexed integer array nums.

  • The low score of nums is the minimum value of |nums[i] - nums[j]| over all 0 <= i < j < nums.length.
  • The high score of nums is the maximum value of |nums[i] - nums[j]| over all 0 <= i < j < nums.length.
  • The score of nums is the sum of the high and low scores of nums.

To minimize the score of nums, we can change the value of at most two elements of nums.

Return the minimum possible score after changing the value of at most two elements of nums.

Note that |x| denotes the absolute value of x.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minimizeSum(vector<int>& nums) {
sort(begin(nums), end(nums));
int n = nums.size();
if(n == 3) return 0;
int res = INT_MAX;
for(int i = 0, j = n - 3; i < 3; i++,j++) {
res = min(res, nums[j] - nums[i]);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/19/PS/LeetCode/minimum-score-by-changing-two-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.