Problem Description
Given an integer array nums, you are allowed to change exactly two elements to any value. The score of the array is defined as the sum of:
- The low score: the minimum absolute difference between any two integers in nums.
- The high score: the maximum absolute difference between any two integers in nums. Return the minimum possible score after performing exactly two changes.
Key Insights
- Sorting the array lets you quickly access the extreme (smallest and largest) values.
- With two changes, you can adjust the “extremes” by either: • Changing the two smallest elements, • Changing the two largest elements, or • Changing one smallest and one largest.
- In each scenario, the low score can be forced to 0 (by duplicating a value) so the overall score is determined by the range (high score) of the remaining elements.
- Thus, after sorting, consider three candidate strategies: • Option 1: Set the two smallest equal to the third smallest, making the new minimum nums[2]. The score is nums[n-1] - nums[2]. • Option 2: Set the two largest equal to the third largest, making the new maximum nums[n-3]. The score is nums[n-3] - nums[0]. • Option 3: Change one smallest and one largest so that the new extremes become nums[1] and nums[n-2]. The score is nums[n-2] - nums[1].
Space and Time Complexity
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) (or O(1) if sorting is done in-place).
Solution
Sort the array to determine the order of elements and evaluate three scenarios corresponding to which two elements are changed. For each:
- When changing the two smallest, the new minimum becomes the third smallest element.
- When changing the two largest, the new maximum becomes the third largest element.
- When changing one smallest and one largest, the new extremes become the second smallest and second largest. Since the low score can be forced to 0 by making duplicate values, the overall score is the difference between the resulting maximum and minimum. The final answer is the minimum score among these three computed ranges.