范围内整数的最大得分

用二分查找锁定最大可能的最小差值,验证该差值是否能满足每个区间的选择限制

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;
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务