Maximize Score of Numbers in Ranges - Problem

You are given an array of integers start and an integer d, representing n intervals [start[i], start[i] + d].

You are asked to choose n integers where the i-th integer must belong to the i-th interval. The score of the chosen integers is defined as the minimum absolute difference between any two integers that have been chosen.

Return the maximum possible score of the chosen integers.

Input & Output

Example 1 — Basic Case
$ Input: start = [4, 6, 8], d = 2
Output: 2
💡 Note: Intervals are [4,6], [6,8], [8,10]. We can choose integers 4, 6, 8 with minimum difference = min(|6-4|, |8-6|, |8-4|) = min(2, 2, 4) = 2
Example 2 — Same Start Points
$ Input: start = [2, 6, 8], d = 0
Output: 2
💡 Note: With d=0, each interval contains only one integer: [2,2], [6,6], [8,8]. We must choose 2, 6, 8 with minimum difference = min(|6-2|, |8-6|, |8-2|) = min(4, 2, 6) = 2
Example 3 — Overlapping Intervals
$ Input: start = [6, 13, 18], d = 10
Output: 3
💡 Note: Intervals are [6,16], [13,23], [18,28]. Optimal selection might be 6, 16, 19 giving minimum difference = min(|16-6|, |19-16|, |19-6|) = min(10, 3, 13) = 3

Constraints

  • 1 ≤ start.length ≤ 104
  • 0 ≤ start[i] ≤ 108
  • 0 ≤ d ≤ 109

Visualization

Tap to expand
Maximize Score of Numbers in Ranges INPUT start = [4, 6, 8], d = 2 0 4 6 8 10 [4, 6] [6, 8] [8, 10] start[0]=4 --> [4, 6] start[1]=6 --> [6, 8] start[2]=8 --> [8, 10] n = 3 intervals ALGORITHM (Greedy) 1 Sort intervals Already sorted: [4,6,8] 2 Binary search on score Check if score k is feasible 3 Greedy selection Pick smallest valid num 4 Verify min diff >= k Return max valid k Trace (score=2): i=0: pick 4 from [4,6] i=1: need >=6, pick 6 i=2: need >=8, pick 8 Chosen: [4, 6, 8] OK Min diff: 2 FINAL RESULT Optimal Selection: 4 6 8 diff=2 diff=2 Output: 2 Maximum min difference achievable is 2 Status: OK Key Insight: Use binary search to find the maximum score k. For each candidate k, greedily check if we can select integers from sorted intervals such that consecutive selections differ by at least k. For each interval, pick the smallest valid number >= (previous + k). If valid selection exists, k is feasible. TutorialsPoint - Maximize Score of Numbers in Ranges | Greedy + Binary Search Approach
Asked in
Google 15 Amazon 12 Meta 8
18.5K Views
Medium Frequency
~35 min Avg. Time
580 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