Skip to content

Commit 68ae78e

Browse files
authored
Create maximize-score-of-numbers-in-ranges.cpp
1 parent e3f8785 commit 68ae78e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(nlogn + nlogr) = O(nlogr)
2+
// Space: O(1)
3+
4+
// binary search, greedy
5+
class Solution {
6+
public:
7+
int maxPossibleScore(vector<int>& start, int d) {
8+
const auto& binary_search_right = [](int left, int right, const auto& check) {
9+
while (left <= right) {
10+
int mid = left + (right - left) / 2;
11+
if (!check(mid)) {
12+
right = mid - 1;
13+
} else {
14+
left = mid + 1;
15+
}
16+
}
17+
return right;
18+
};
19+
20+
sort(begin(start), end(start));
21+
return binary_search_right(1, (start.back() + d) - start.front(), [&](int x) {
22+
int64_t curr = start[0];
23+
for (int i = 1; i < size(start); ++i) {
24+
curr = max(curr + x, static_cast<int64_t>(start[i]));
25+
if (curr > start[i] + d) {
26+
return false;
27+
}
28+
}
29+
return true;
30+
});
31+
}
32+
};

0 commit comments

Comments
 (0)