Minimum Difference Between Largest and Smallest Value in Three Moves (LeetCode 1509): Solution and Explanation

Medium
Array
Greedy
Sorting

Change at most three elements to any values so that the gap between the largest and smallest value is as small as possible, and return that gap.

Intuition

A changed element can be set to a value already inside the range of the others, so changing it is the same as deleting it.

Deleting a middle value never shrinks the spread. Only the extremes matter, so after sorting the three deleted values are some of the 3 smallest and some of the 3 largest.

That leaves just four choices: delete k from the bottom and 3 - k from the top, for k = 0, 1, 2, 3. Each leaves a window nums[k] to nums[n - 4 + k].

Approach: Sort and check four windows

  1. If there are at most 4 numbers, move three of them onto the fourth and return 0.
  2. Sort nums.
  3. For k from 0 to 3, compute nums[n - 4 + k] - nums[k].
  4. Return the smallest of the four spreads.

Step-by-step example

nums = [20,66,68,57,45,18,42,34,37,58]
  1. Sorted: [18,20,34,37,42,45,57,58,66,68], n = 10.
  2. k = 0: drop the top 3, window 18..57, spread 39.
  3. k = 1: drop 18 and the top 2, window 20..58, spread 38.
  4. k = 2: drop 18, 20 and 68, window 34..66, spread 32.
  5. k = 3: drop 18, 20, 34, window 37..68, spread 31.
  6. Return 31.

Code: Python, Java, C++

1class Solution:
2    def minDifference(self, nums: List[int]) -> int:
3        n = len(nums)
4        if n <= 4:
5            return 0
6        nums.sort()
7        best = nums[-1] - nums[0]
8        for left in range(4):
9            right = n - 4 + left
10            best = min(best, nums[right] - nums[left])
11        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates. The four window checks are constant work.

Space

O(1)

Only a few variables beyond the in-place sort.

Other approaches

Partial selection of the 4 smallest and 4 largest (time O(n), space O(1))

Only the 4 smallest and 4 largest values matter, so a heap of size 4 on each side (or two nth_element calls) finds them without a full sort.

Brute force over which three to change (time O(n^4), space O(1))

Try every triple of indices to change and compute the spread of the rest. Correct but far too slow for large inputs.

Common mistakes

  • Forgetting the n <= 4 case, where the window indices go out of range and the answer is 0.
  • Only trying to drop the 3 largest or the 3 smallest, missing the mixed splits.
  • Thinking a move must change a value by a fixed amount. A move sets the element to any value.
  • Using a windowed difference with the wrong right edge. With 3 removals the kept window is n - 3 elements, ending at index n - 4 + k.

Frequently asked questions

Why is changing an element the same as removing it?

Set it equal to any value already in the kept window. It then cannot be a new maximum or minimum, so it does not affect the spread.

Can the difference overflow a 32-bit int?

Values lie in [-10^9, 10^9], so the largest possible difference is 2 * 10^9, which still fits below 2^31 - 1.

What if fewer than three moves are best?

Using all three never hurts, because removing an extra element cannot widen the window. Checking the four 3-move splits covers every case.