1011. Capacity To Ship Packages Within D Days

题目 1011. Capacity To Ship Packages Within D Days

image-d6002397

思路分析

代码实现

class Solution {

   private boolean check(int capacity, int[] weights, int days) {
        int cnt = 1; 
        int currentLoad = 0;
        
        for (int w : weights) {
            if (currentLoad + w > capacity) {
                cnt++;
                currentLoad = w;
            } else {
                currentLoad += w;
            }
        }
        return cnt <= days;
    }

    public int shipWithinDays(int[] weights, int days) {
        int maxv=0,sumv=0;
        for(int w:weights){
            maxv=Math.max(w,maxv);
            sumv+=w;
        }

        int l=maxv,r=sumv;

        while(l<r){
            int mid=l+r>>1;
            if(check(mid,weights,days)){
                r=mid;
            }else{
                l=mid+1;
            }
        }
        return r;
    }
}

同类题型

视频讲解