Skip to main content

Command Palette

Search for a command to run...

shipment

Published
1 min readView as Markdown
class Solution {
    public int shipWithinDays(int[] weights, int days) {
        int left = 0, right = 0;
        for (int w : weights) {
            left = Math.max(left, w);  // at least the heaviest package
            right += w;                // at most sum of all weights
        }

        while (left < right) {
            int mid = left + (right - left) / 2;
            if (canShip(weights, days, mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    // helper to check how many days needed with capacity cap
    private boolean canShip(int[] weights, int days, int cap) {
        int usedDays = 1, current = 0;
        for (int w : weights) {
            if (current + w > cap) {
                usedDays++;
                current = 0;
            }
            current += w;
            if (usedDays > days) return false;
        }
        return true;
    }
}

More from this blog

Amit singh's blog

235 posts