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
Understanding the Visualization
1
Input
Array with various elements creating a large range
2
Strategy
Remove or change extreme values to minimize range
3
Output
Minimum possible difference after 3 moves
Key Takeaway
🎯 Key Insight: With 3 moves on arrays ≤4 elements, we can make all elements equal (difference=0). For larger arrays, greedily remove extreme values.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code