#3281
Maximize Score of Numbers in Ranges
MediumArrayBinary SearchGreedySortingBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(max(start) + d)) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log(max(start) + d))Space O(1)
The optimal approach uses binary search to maximize the minimum absolute difference between chosen integers. By sorting the start array and strategically selecting integers within their ranges, we can efficiently find the best configuration.
⚙️
Algorithm
3 steps- 1Step 1: Sort the start array.
- 2Step 2: Use binary search to find the maximum possible score (x).
- 3Step 3: For each mid value in the binary search, check if it's possible to select integers such that the minimum difference is at least mid.
solution.py20 lines
1# Full working Python code
2def canChoose(start, d, x):
3 last_chosen = start[0]
4 for i in range(1, len(start)):
5 next_chosen = last_chosen + x
6 if next_chosen > start[i] + d:
7 return False
8 last_chosen = max(start[i], next_chosen)
9 return True
10
11def maxScore(start, d):
12 start.sort()
13 left, right = 0, 10**9 + 1
14 while left < right:
15 mid = (left + right + 1) // 2
16 if canChoose(start, d, mid):
17 left = mid
18 else:
19 right = mid - 1
20 return leftℹ
Complexity note: The binary search runs in logarithmic time relative to the maximum possible score, and for each mid value, we check the feasibility in linear time.
- 1Sorting the start array helps in efficiently checking the feasibility of choosing integers.
- 2Binary search allows us to systematically explore potential scores without generating all combinations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.