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 - Greedy Optimization INPUT nums array: 1 i=0 3 i=1 6 i=2 k = 3 For each element: nums[i] + k OR nums[i] - k Initial range: 6 - 1 = 5 ALGORITHM STEPS 1 Sort Array [1, 3, 6] 2 Base Score max - min = 6-1 = 5 3 Try Split Points Left +k, Right -k 4 Find Minimum Compare all splits Split Calculations: i=0: [1+3]=4, [3-3,6-3]=[0,3] high=max(6-3,1+3)=4 low=min(1+3,3-3)=0 range = 4-0 = 4 Best split gives range = 3 FINAL RESULT Optimal transformation: 1+3 3+3 6-3 Results in: 4 6 3 max = 6, min = 3 Score = 6 - 3 = 3 Output: 3 OK - Minimum Score Key Insight: After sorting, we try splitting the array at each position: elements before split get +k, elements after get -k. The optimal split minimizes the difference between the new max and min. This greedy approach works because sorted order reveals where to split for minimum range. TutorialsPoint - Smallest Range II | Greedy Optimization Approach
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