Smallest Range I - Problem

You are given an integer array nums and an integer k.

In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k].

You can apply this operation at most once for each index i.

The score of nums is the difference between the maximum and minimum elements in nums.

Return the minimum score of nums after applying the mentioned operation at most once for each index in it.

Input & Output

Example 1 — Range Can Be Eliminated
$ Input: nums = [1], k = 0
Output: 0
💡 Note: Single element array has range 0. No adjustments needed since range is already minimized.
Example 2 — Range Reduced to Zero
$ Input: nums = [0,10], k = 2
Output: 6
💡 Note: Original range is 10-0=10. Best adjustments: 0+2=2, 10-2=8. New range is 8-2=6.
Example 3 — Large k Value
$ Input: nums = [1,3,6], k = 3
Output: 0
💡 Note: Original range is 6-1=5. With k=3, we can adjust: 1+3=4, 3+0=3, 6-3=3. All values become close enough to achieve range 0.

Constraints

  • 1 ≤ nums.length ≤ 104
  • 0 ≤ nums[i] ≤ 104
  • 0 ≤ k ≤ 104

Visualization

Tap to expand
Smallest Range I: Minimize Array Range with AdjustmentsStep 1: Original Array136Range: 6-1=5, k=3Step 2: Optimal Adjustments433Adjustments: [+3, 0, -3]Apply StrategyMathematical Formula:max(0, (max-min) - 2k)max(0, 5 - 6) = 0Minimum Range: 0All elements can be brought to same value
Understanding the Visualization
1
Input
Array [1,3,6] with adjustment limit k=3
2
Process
Optimize by moving min up and max down by k
3
Output
Minimum possible range after adjustments
Key Takeaway
🎯 Key Insight: Move minimum up by k and maximum down by k to minimize the range optimally
Asked in
Google 15 Amazon 12 Facebook 8
35.0K Views
Medium Frequency
~15 min Avg. Time
872 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