#910
Smallest Range II
MediumArrayMathGreedySortingGreedySortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal approach focuses on sorting the array and adjusting the maximum and minimum values intelligently. By considering the largest and smallest elements after adjustments, we can directly compute the minimum score without generating all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array nums.
- 2Step 2: Calculate the potential new maximum and minimum values after adding or subtracting k.
- 3Step 3: The minimum score will be the minimum of the difference between the adjusted maximum and minimum.
solution.py7 lines
1# Full working Python code
2
3def smallestRangeII(nums, k):
4 nums.sort()
5 min_val = nums[0] + k
6 max_val = nums[-1] - k
7 return max(0, max_val - min_val)ℹ
Complexity note: The time complexity is dominated by the sorting step, which is O(n log n). The rest of the operations are O(n) or constant time.
- 1Adjusting both the maximum and minimum values allows for a more controlled reduction in score.
- 2Sorting the array helps in easily identifying the potential new maximum and minimum values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.