Minimum Difference Between Largest and Smallest Value in Three Moves - Problem

You are given an integer array nums.

In one move, you can choose one element of nums and change it to any value.

Return the minimum difference between the largest and smallest value of nums after performing at most three moves.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,3,2,4]
Output: 0
💡 Note: We can change elements to make them all equal. For instance, change 5→3, 2→3, 4→3. Result: [3,3,3,3] with difference = 3-3 = 0.
Example 2 — Optimal Removal
$ Input: nums = [1,5,0,10,14]
Output: 1
💡 Note: Sort: [0,1,5,10,14]. Try removing 3 extremes: remove 0,10,14 → [1,5] with difference = 5-1 = 4. Or remove 14,10,0 → [1,5] = 4. Best is remove 0,1,14 → [5,10] = 5, or remove 14,10,5 → [0,1] = 1.
Example 3 — Small Array
$ Input: nums = [6,6,0,1,1,4,6]
Output: 2
💡 Note: Sort: [0,1,1,4,6,6,6]. Remove 3 elements optimally: remove 0,6,6 → [1,1,4,6] with difference = 6-1 = 5. Better: remove 0,1,6 → [1,4,6,6] = 5. Best: remove 6,6,6 → [0,1,1,4] = 4-0 = 4. Actually optimal is remove 0,6,6 → [1,1,4,6] then change to get difference 2.

Constraints

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

Visualization

Tap to expand
Min Difference After 3 Moves INPUT Integer Array nums 5 idx 0 3 idx 1 2 idx 2 4 idx 3 Sorted Array: 2 min 3 4 5 max nums = [5, 3, 2, 4] Length: 4, Moves: 3 ALGORITHM STEPS 1 Sort Array Order elements ascending 2 Check Length If n <= 4: return 0 3 Try 4 Strategies Remove extremes combinations Remove 3 left: nums[n-1]-nums[3] Remove 2L,1R: nums[n-2]-nums[2] Remove 1L,2R: nums[n-3]-nums[1] Remove 3 right: nums[n-4]-nums[0] 4 Return Minimum Best of all 4 strategies n=4, so 4 <= 4 All elements changeable! FINAL RESULT With 3 moves on array of 4: X X X X All elements can be same value max - min = X - X = 0 Output: 0 [OK] Verified Minimum difference = 0 Key Insight: Greedy approach: Always target extremes (largest or smallest values) for removal. After sorting, we only need to consider 4 combinations of removing elements from ends: remove 0,1,2 from left | remove 0,1 left + n-1 right | remove 0 left + n-1,n-2 right | remove n-1,n-2,n-3 TutorialsPoint - Minimum Difference Between Largest and Smallest Value in Three Moves | Greedy Approach
Asked in
Google 23 Amazon 18 Microsoft 15 Apple 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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