Minimum Score by Changing Two Elements - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,3]
Output: 0
💡 Note: Change nums to [4,4,4]. Low score = 0 (min difference), High score = 0 (max-min), Total = 0+0 = 0
Example 2 — Different Values
$ Input: nums = [1,4,7,8,5]
Output: 3
💡 Note: Change to [4,4,5,5,5]. Low score = 1 (difference between 4 and 5), High score = 1 (5-4), Total = 1+1 = 2. Actually optimal is changing to get score 3.
Example 3 — Small Array
$ Input: nums = [10,20]
Output: 0
💡 Note: Change both elements to same value, e.g., [20,20]. Low score = 0, High score = 0, Total = 0

Constraints

  • 3 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Score by Changing Two Elements INPUT Array: nums 1 idx 0 4 idx 1 3 idx 2 Score Definitions: Low = min absolute diff High = max absolute diff Score = Low + High Goal: Minimize score by changing 2 elements ALGORITHM STEPS 1 Sort Array [1, 4, 3] --> [1, 3, 4] 2 Check Array Size n=3, if n<=3 return 0 3 Why n<=3? Change 2 to match 1 All same --> diff=0 4 General Case (n>3) Try removing extremes: Option A: Remove 2 left Option B: Remove 1 each side Option C: Remove 2 right Return min of all options FINAL RESULT Original: [1, 4, 3] Sorted: [1, 3, 4] 1 3 4 change change 3 3 3 All elements same! Output: 0 Low=0, High=0, Score=0 Key Insight: For arrays with 3 or fewer elements, we can change 2 elements to match the remaining one, making all elements identical. This results in both low and high scores being 0, giving minimum score = 0. For larger arrays, the greedy approach removes extremes from sorted array to minimize range. TutorialsPoint - Minimum Score by Changing Two Elements | Optimized Greedy
Asked in
Google 25 Meta 18 Amazon 15
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen