MediumNo. 1509

Minimum Difference Between Largest and Smallest Value in Three Moves — LeetCode 1509 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Sorting
Reading time
2 min

The problem

You are given an integer array nums. In one move, you can choose one element of nums and change it to any value.

Example

Input
nums = [5,3,2,4]
Output
0
Explanation
We can make at most 3 moves.

Python solution

PythonSolution
class Solution:
    def minDifference(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 5:
            return 0
        nums.sort()
        ans = inf
        for l in range(4):
            r = 3 - l
            ans = min(ans, nums[n - 1 - r] - nums[l])
        return ans

Complexity

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0452Minimum Number of Arrows to Burst BalloonsMedium
0455Assign CookiesEasy
0502IPOHard
0561Array PartitionEasy

Frequently asked questions

How hard is LeetCode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves?

LeetCode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves is rated Medium on LeetCode.

What topics does LeetCode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves cover?

LeetCode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.