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
Number Line Strategy: Minimize the Range05101520136Original Array: [1, 3, 6], k = 3051015201 โ†’ 4 (+3)6 โ†’ 3 (-3)43After Optimal Adjustments: Ranges Overlap!Mathematical FormulaResult = max(0, max_val - min_val - 2k)= max(0, 6 - 1 - 6) = max(0, -1) = 0โœ“ All numbers can converge to the same value!๐Ÿ’ก Key InsightWhen 2k โ‰ฅ (max - min), we can make all elements equal. Otherwise, some gap remains.
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!
Asked in
Google 35 Amazon 28 Apple 22 Microsoft 18
23.5K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen