leetcode_1011. Capacity To Ship Packages Within D Days_binary search二分

https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/

传送带每天有最大传送量V,对于n个货物[w1,w2,w3...wn],要在D天内将所有货物传送完的V最小为多少?

二分每天最大传送量V,初始:Vhigh = sum(w),Vlow = max(w)。

class Solution
{
public:
    int calc_days(vector<int>& weights, int V)
    {
        int len = weights.size(), days=0, i=0, cur=0;
        while(i<len)
        {
            if(cur+weights[i] > V)
            {
                days++;
                cur=0;
            }
            cur += weights[i++];
        }
        if(cur>0)
            days++;
        return days;
    }

    int shipWithinDays(vector<int>& weights, int D)
    {
        int high=0, lenw=weights.size(), low=0;
        for(int i=0; i<lenw; i++)
        {
            high += weights[i];
            low = max(low, weights[i]);
        }
        int res=0;
        while(low<=high)
        {
            int mid = (high+low)>>1;
            if(D >= calc_days(weights, mid))
            {
                high = mid-1;
                res = mid;
            }
            else
                low = mid+1;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/jasonlixuetao/p/10696117.html