Minimum Score by Changing Two Elements Problem
#2567
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2567.
You 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] and nums[1] to be 6 so that nums becomes [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] and nums[2] to 1 so that nums becomes [1,1,1].
- The sum of maximum absolute difference and minimum absolute difference is 0.
Constraints:
3 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Sorting + Greedy
After sorting, the minimum difference between two elements can always be made 0 (change an element to equal another one), so the score is just max minus min. We may change two elements, so we effectively remove two elements from the sorted array, and there are only three sensible choices: drop the two smallest, the two largest, or the smallest and the largest.
The remaining ranges are nums[n-1] - nums[2], nums[n-3] - nums[0] and nums[n-2] - nums[1]; return the smallest.
Complexity: time O(n log n), space O(log n), where n is the length of nums.
class Solution:
def minimizeSum(self, nums: List[int]) -> int:
nums.sort()
a = abs(nums[-3] - nums[0])
b = abs(nums[-2] - nums[1])
c = abs(nums[-1] - nums[2])
return min(a, b, c)