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

You're given an integer array nums and have the power to transform it strategically. In each move, you can change any element to any value you want - there are no restrictions!

Your mission is to minimize the difference between the largest and smallest values in the array after making at most 3 moves.

Key insight: Since you can change elements to any value, the optimal strategy is to either remove the largest elements or the smallest elements (or a combination) to minimize the range.

Input: An integer array nums
Output: The minimum possible difference between max and min values after at most 3 moves

Example: For [5,3,2,4], you can change 5 to 3, making the array [3,3,2,4]. The difference becomes 4-2=2.

Input & Output

example_1.py โ€” Basic Case
$ Input: [5, 3, 2, 4]
โ€บ Output: 0
๐Ÿ’ก Note: We can change one element to 3, making the array [3,3,2,4] with difference 2. But optimally, we can make all elements equal: [3,3,3,3] using 3 moves, resulting in difference 0.
example_2.py โ€” Large Range
$ Input: [1, 5, 0, 10, 14]
โ€บ Output: 1
๐Ÿ’ก Note: After sorting: [0,1,5,10,14]. We can remove the 3 largest elements (5,10,14) leaving [0,1] with difference 1. Or remove 2 largest + 1 smallest leaving [1,5] with difference 4. The minimum is 1.
example_3.py โ€” Small Array Edge Case
$ Input: [3, 100, 20]
โ€บ Output: 0
๐Ÿ’ก Note: With only 3 elements, we can change all of them in 3 moves to make them equal, resulting in difference 0.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • You have exactly 3 moves maximum
  • Each move allows changing any element to any value

Visualization

Tap to expand
๐Ÿ”๏ธ Mountain Range Leveling StrategyPeak 1Height: 5Peak 2Height: 3Peak 3Height: 2Peak 4Height: 4๐Ÿšœ Bulldozer StrategyOption 1: Level 3 tallest peaksOption 2: Level 3 shortest peaksOption 3: Level 2 tall + 1 shortOption 4: Level 1 tall + 2 shortChoose the best option!After Leveling: All peaks same height = 0 difference!
Understanding the Visualization
1
Survey the Range
Sort the mountains by height to identify the extreme peaks
2
Strategic Planning
Consider 4 strategies: level 3 tallest, 3 shortest, or mixed approaches
3
Execute Optimal Plan
Choose the strategy that results in the smallest height difference
4
Measure Success
Calculate the final range after leveling
Key Takeaway
๐ŸŽฏ Key Insight: Focus on extreme values! Since we can set any height, we only need to consider removing the tallest or shortest peaks to minimize the range efficiently.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
41.2K Views
Medium-High Frequency
~15 min Avg. Time
1.8K 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