范围内整数的最大得分
用二分查找锁定最大可能的最小差值,验证该差值是否能满足每个区间的选择限制
class Solution {
public:
bool check(long long lim,vector<int>& start,int d) {
long long now = start[0];
for (int i = 1; i < start.size(); i++) {
now = max(now + lim, 1LL * start[i]);
if (now > start[i] + d) return false;
}
return true;
};
int maxPossibleScore(vector<int>& start, int d) {
sort(start.begin(), start.end()); // 先排序区间左端点
long long head = 0, tail = 2e9; // 二分范围
while (head < tail) {
long long mid = (head + tail + 1) >> 1; // 向上取整的二分
if (check(mid,start,d)) head = mid; // 能满足则尝试更大的lim
else tail = mid - 1; // 不能满足则缩小lim
}
return head;
}
};
查看5道真题和解析