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

MediumGreedyArraySorting
Problem
#1509
Pattern
Greedy
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

Python
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

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

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

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.

Get Stealth Interview