Leetcode 1011. 在 D 天内送达包裹的能力 题解

题目链接:添加链接描述
在这里插入图片描述
在这里插入图片描述
二分搜运力:左指针初始化为最大重量(不然最大的那个运不了),右指针初始化为总重量(假设一天全运完)

每次贪心计算当前运力需要的最大天数(因为要求最小运力,所以贪心时直接求最大天数即可),并更新左右指针

代码如下:

class Solution {
public:
    int shipWithinDays(vector<int>& weights, int D) {
        int left = *max_element(weights.begin(), weights.end());
        //accumulate: 从weights.begin() 到 weights.end()求累加和,初始值为0
        int right = accumulate(weights.begin(), weights.end(), 0);
        int res = INT_MAX;

        while(left<=right){
            int mid = (left + right) / 2;
            int temp = 0, day = 0;
            for(int i = 0; i < weights.size(); i++) {
                temp += weights[i];
                if(temp > mid) {
                    day++;
                    temp = weights[i];
                }
            }
            day++;

            if(day > D) {
                left = mid + 1;
            } else {
                right = mid - 1;
                res = min(res, mid);
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42396397/article/details/105931785
今日推荐