leetcode 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;
    }
}	
posted on 2019-03-20 23:29  王 帅  阅读(119)  评论(0编辑  收藏  举报