Description
Minimum Score by Changing Two Elements
MediumYou are given an integer array nums.
- The low score of
numsis the minimum absolute difference between any two integers. - The high score of
numsis the maximum absolute difference between any two integers. - The score of
numsis the sum of the high and low scores.
Return the minimum score after changing two elements of nums.
Example 1:
Input: nums = [1,4,7,8,5]
Output: 3
Explanation:
- Change
nums[0]andnums[1]to be 6 so thatnumsbecomes [6,6,7,8,5]. - The low score is the minimum absolute difference: |6 - 6| = 0.
- The high score is the maximum absolute difference: |8 - 5| = 3.
- The sum of high and low score is 3.
Example 2:
Input: nums = [1,4,3]
Output: 0
Explanation:
- Change
nums[1]andnums[2]to 1 so thatnumsbecomes [1,1,1]. - The sum of maximum absolute difference and minimum absolute difference is 0.
Constraints:
3 <= nums.length <= 1051 <= nums[i] <= 109
Solutions
Interesting exercise, possible to do without sort by finding lowest and highest 3 numbers. I didn't have the time.
Language: javascript()DONE
CPU Performance49.54%
x
Memory Performance64.53%
x
/**
* @param {number[]} nums
* @return {number}
*/
var minimizeSum = function(nums) {
nums.sort((a, b) => a - b);
const n = nums.length;
const diff = nums[n - 1] - nums[0];
const oneLeft = nums[1] - nums[0];
const twoLeft = nums[2] - nums[1] + oneLeft;
const oneRight = nums[n - 1] - nums[n - 2];
const twoRight = nums[n - 2] - nums[n - 3] + oneRight;
return diff - Math.max(
oneLeft + oneRight,
twoLeft,
twoRight
);
};