Maximize Score of Numbers in Ranges Problem
Description
LeetCode Problem 3281.
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.
Example 1:
Input: start = [6,0,3], d = 2
Output: 4
Explanation:
The maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is min(|8 - 0|, |8 - 4|, |0 - 4|) which equals 4.
Example 2:
Input: start = [2,6,13,13], d = 5
Output: 5
Explanation:
The maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|) which equals 5.
Constraints:
2 <= start.length <= 10^50 <= start[i] <= 10^90 <= d <= 10^9
Solution
Approach: Sorting + Binary Search
Sort start. The score is the smallest gap between two chosen numbers, and if a score x is achievable then so is every smaller one, so binary search the largest achievable score between 0 and start[-1] + d - start[0].
To check a candidate mi, choose numbers greedily from left to right, each as small as possible: keep last, the previous choice. For the next interval [st, st + d], if last + mi > st + d the gap cannot be kept and the check fails; otherwise choose max(st, last + mi).
Complexity: O(n log M) time and O(1) extra space, where M is the largest possible score.
from math import inf
class Solution:
def maxPossibleScore(self, start: List[int], d: int) -> int:
def check(mi: int) -> bool:
last = -inf
for st in start:
if last + mi > st + d:
return False
last = max(st, last + mi)
return True
start.sort()
l, r = 0, start[-1] + d - start[0]
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l