2567. Minimum Score by Changing Two Elements
Description
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
.
Example 1:
Input: nums = [1,4,7,8,5]
Output: 3
Explanation:
- Change
nums[0]
andnums[1]
to be 6 so thatnums
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]
andnums[2]
to 1 so thatnums
becomes [1,1,1]. - The sum of maximum absolute difference and minimum absolute difference is 0.
Constraints:
3 <= nums.length <= 105
1 <= nums[i] <= 109
Solutions
Solution 1: Sorting + Greedy
From the problem description, we know that the minimum score is actually the minimum difference between two adjacent elements in the sorted array, and the maximum score is the difference between the first and last elements of the sorted array. The score of the array $nums$ is the sum of the minimum score and the maximum score.
Therefore, we can first sort the array. Since the problem allows us to modify the values of at most two elements in the array, we can modify a number to make it the same as another number in the array, making the minimum score $0$. In this case, the score of the array $nums$ is actually the maximum score. We can choose to make one of the following modifications:
Modify the smallest two numbers to $nums[2]$, then the maximum score is $nums[n - 1] - nums[2]$; Modify the smallest number to $nums[1]$ and the largest number to $nums[n - 2]$, then the maximum score is $nums[n - 2] - nums[1]$; Modify the largest two numbers to $nums[n - 3]$, then the maximum score is $nums[n - 3] - nums[0]$. Finally, we return the minimum score of the above three modifications.
The time complexity is $O(n \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$.
Similar problems:
-1509. Minimum Difference Between Largest and Smallest Value in Three Moves
1 2 3 4 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 |
|
1 2 3 4 5 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 |
|