Minimum Difference Between Largest and Smallest Value in Three Moves — LeetCode 1509 Python Solution
MediumGreedyArraySorting
- Problem
- #1509
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(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.