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 - Optimal Solution INPUT 1 nums[0] Input Values nums = [1] k = 0 Array length: 1 Single element array max = min = 1 ALGORITHM STEPS 1 Find Range max(nums) - min(nums) range = 1 - 1 = 0 2 Calculate 2*k Max reduction possible 2 * k = 2 * 0 = 0 3 Compare Values range vs 2*k 0 vs 0 4 Return Result max(0, range - 2*k) max(0, 0-0) = 0 Formula: max(0, (max-min) - 2*k) FINAL RESULT Minimum Score 0 Explanation With single element: - max = min = 1 - Difference = 0 - No change needed OK Optimal Solution Key Insight: Each element can be adjusted by [-k, k]. To minimize the range, increase min by k and decrease max by k. This reduces the range by 2*k. If range is already less than or equal to 2*k, we can make it 0. Result = max(0, (max - min) - 2*k) | Time: O(n) | Space: O(1) TutorialsPoint - Smallest Range I | Optimal Solution
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