1014. Capacity To Ship Packages Within D Days

class Solution {
    public int shipWithinDays(int[] weights, int D) {
        int left = 1, right = 50000;
        int N = weights.length;
        for (int i = 0; i < N; ++i) {
            left = Math.max(left, weights[i]);
            right += weights[i];
        }
        while (left < right) {
            int mid = (left + right) / 2;
            int count = helper(weights, mid);
            if (count <= D) {
                right = mid;
            }
            else {
                left = mid + 1;
            }
        }
        return left;
    }
    
    int helper(int[] w, int cap) {
        int total = 0;
        int count = 0;
        for (int i = 0; i < w.length; ++i) {
            if (w[i] + total > cap) {
                count += 1;
                total = w[i];
            }
            else {
                total += w[i];
            }
        }
        count += 1;
        return count;
    }
}   

猜你喜欢

转载自www.cnblogs.com/exhausttolive/p/10568883.html