Smallest Range II - Problem

You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.

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

Return the minimum score of nums after changing the values at each index.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,6], k = 3
Output: 3
💡 Note: After changes: [1+3, 3+3, 6-3] = [4,6,3]. Range = max(4,6,3) - min(4,6,3) = 6-3 = 3
Example 2 — All Same Operation
$ Input: nums = [0,10], k = 2
Output: 6
💡 Note: Best choice: [0+2, 10-2] = [2,8]. Range = 8-2 = 6. (Better than [2,12] range=10 or [-2,8] range=10)
Example 3 — Single Element
$ Input: nums = [1], k = 0
Output: 0
💡 Note: Only one element, so range is always 0 regardless of operations

Constraints

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

Visualization

Tap to expand
Smallest Range II: Minimize Array Range After ±k Operations136Original: [1,3,6], Range = 6-1 = 5k = 34631+33+36-3Optimal: [4,6,3], Range = 6-3 = 3Strategy:1. Each element: choose +k or -k2. Goal: minimize max - min3. Sort + try all split points4. O(n log n) optimal solution
Understanding the Visualization
1
Input
Array [1,3,6] with k=3, current range = 5
2
Transform
Each element can become nums[i]+k or nums[i]-k
3
Optimize
Find assignment that minimizes max-min
Key Takeaway
🎯 Key Insight: Sort first, then find the optimal split point where prefix adds k and suffix subtracts k
Asked in
Google 25 Facebook 18 Amazon 12
23.4K Views
Medium Frequency
~25 min Avg. Time
867 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