MediumNo. 0910
Smallest Range II — LeetCode 910 Python Solution
- Pattern
- Greedy
- Topics
- Greedy, Array, Math, Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.
Example
- Input
- nums = [1], k = 0
- Output
- 0
- Explanation
- The score is max(nums) - min(nums) = 1 - 1 = 0.
Python solution
class Solution:
def smallestRangeII(self, nums: List[int], k: int) -> int:
nums.sort()
ans = nums[-1] - nums[0]
for i in range(1, len(nums)):
mi = min(nums[0] + k, nums[i] - k)
mx = max(nums[i - 1] + k, nums[-1] - k)
ans = min(ans, mx - mi)
return ansComplexity
- Time
- O(n × log n)
- Space · auxiliary
- O(log n)where n is the length of the array
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 910. Smallest Range II 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
| No. | Problem | Difficulty |
|---|---|---|
| 0976 | Largest Perimeter Triangle | Easy |
| 1561 | Maximum Number of Coins You Can Get | Medium |
| 1686 | Stone Game VI | Medium |
| 2195 | Append K Integers With Minimal Sum | Medium |
| 2607 | Make K-Subarray Sums Equal | Medium |
| 2818 | Apply Operations to Maximize Score | Hard |
Frequently asked questions
- How hard is LeetCode 910. Smallest Range II?
LeetCode 910. Smallest Range II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 910. Smallest Range II?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 910. Smallest Range II?
The Python solution on this page uses O(log n), where n is the length of the array auxiliary space.
- What topics does LeetCode 910. Smallest Range II cover?
LeetCode 910. Smallest Range II is tagged Greedy, Array, Math and Sorting on LeetCode.