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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code