For the solution of this problem, we should be able to tell that it need a binary search.

The left value is the maxmum weight in the weight list, because if less than that, the package cannot be shipped.

The right value is the sum of the weight.

The solution's time complexity is log(n), n is the sum of the weight.

    public int shipWithinDays(int[] weights, int days) {
        int l=0, r = 0;
        for (int i = 0; i < weights.length; i++) {
            l = Math.max(l, weights[i]);  //The left is the max value of weights
            r += weights[i];
        }
        int mid = 0, daynum = 0;
        while (l <= r) {
            mid = (l + r) / 2;
            daynum = helper(weights, mid);
            if (daynum <= days) {//even if the daynum == days, there might be smaller value meed the requirement
                r = mid-1;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }


    private int helper(int[] weights, int mid) {
        int sum = 0;
        int i = 0;
        int days = 1;
        while (i < weights.length) {
            sum += weights[i];
            if (sum <= mid)
                i++;
            else {
                days++;
                sum = 0;
            }
        }
        return days;
    }

利用万能模版:

class Solution {
    public int shipWithinDays(int[] weights, int days) {
        int sum = 0;
        int maxWeight=0;
        for(int i=0;i<weights.length;i++){
            sum+=weights[i];
            maxWeight = Math.max(maxWeight, weights[i]);
        }
        
        int l=maxWeight, r = sum;
        while(l+1<r){
            int mid = (l+r)/2;
            int temp = ship(weights, mid);
            if(temp<=days)
                r=mid;
            else
                l = mid;
        }
        int temp = ship(weights, l);
        if(temp<=days)
            return l;
        else
            return r;
    }
    
    private  int ship(int[] weights, int load){
        int res = 0;
        int sum = 0;
        for(int i=0;i<weights.length;i++){
            if(sum+weights[i]>load){
                res++;
                sum=0;
            }
            sum+=weights[i];
        }
        if(sum>0)
            res++;
        return res;
    }
}

 

posted on 2022-02-02 13:55  阳光明媚的菲越  阅读(20)  评论(0编辑  收藏  举报