Smallest Range I - Problem
You are given an integer array nums and an integer k. Your goal is to minimize the score of the array, where the score is defined as the difference between the maximum and minimum elements.
You can perform at most one operation on each element: change nums[i] to nums[i] + x, where x is any integer in the range [-k, k].
What's the strategy? To minimize the range, we want to bring all numbers as close together as possible. The optimal approach is to:
- Increase smaller numbers (add up to
+k) - Decrease larger numbers (add up to
-k) - Move everything toward the middle of the original range
Return the minimum possible score after applying the operations optimally.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1], k = 0
โบ
Output:
0
๐ก Note:
With only one element and k=0, we can't make any changes. The score is max - min = 1 - 1 = 0.
example_2.py โ Can Eliminate Range
$
Input:
nums = [0, 10], k = 2
โบ
Output:
6
๐ก Note:
Original range is 10-0=10. We can increase 0 by 2 to get 2, and decrease 10 by 2 to get 8. New range is 8-2=6.
example_3.py โ Ranges Overlap
$
Input:
nums = [1, 3, 6], k = 3
โบ
Output:
0
๐ก Note:
Min=1 can become 4 (add 3), Max=6 can become 3 (subtract 3). Since 4 > 3, we can make all values equal, so minimum score is 0.
Constraints
- 1 โค nums.length โค 104
- 0 โค nums[i] โค 104
- 0 โค k โค 104
- Follow-up: Can you solve this in O(n) time?
Visualization
Tap to expand
Understanding the Visualization
1
Find the Extremes
Locate the minimum and maximum values in the array - these define our current range
2
Apply Optimal Moves
Move the minimum value as far right as possible (+k) and maximum as far left as possible (-k)
3
Check for Overlap
If the adjusted ranges overlap (min+k โฅ max-k), all numbers can meet at the same point!
4
Calculate Result
If ranges overlap, return 0. Otherwise, return the remaining gap: (max-k) - (min+k)
Key Takeaway
๐ฏ Key Insight: This problem transforms from a complex optimization into simple arithmetic once we realize the optimal strategy is always to maximize adjustments toward the center!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code