其他分享
首页 > 其他分享> > 1011. Capacity To Ship Packages Within D Days

1011. Capacity To Ship Packages Within D Days

作者:互联网

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;
    }

 

标签:Capacity,weight,int,max,sum,Within,Days,value,weights
来源: https://www.cnblogs.com/feiflytech/p/15860288.html