DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 1011. Capacity To Ship Packages Within D Days (javascript solution)

Description:

A conveyor belt has packages that must be shipped from one port to another within D days.

The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.

Solution:

Time Complexity : O(n^2log(n))
Space Complexity: O(1)

   // Binary search approach
var shipWithinDays = function(weights, D) {
    function getDays(capacity) {
        let days = 1, total = 0;

        // See how many days it will take to unload all the weights given the current capacity
        for(let n of weights) {
            total += n;
            // Increase days only when we will exceed the capacity
            if(total > capacity) {
                total = n;
                days++;
            }
        }
        return days;
    }

    // Start is the minimum capacity of one day which is the max of all the weights
    // End is the max capacity we could load on one day which is the sum of all the weights
    let start = Math.max(...weights), 
        end = weights.reduce((acc, cur) => acc + cur, 0);

    // The min cacpaity needed is between start and finish
    while(start < end) {
        const mid = Math.floor((end+start)/2);
        // See how many days it would take to unload all the weigths given mid as the current capacity
        const days = getDays(mid);
        // If capacity at mid took more than D days to load, then we can add more weigth on the ships each day which means we need to increase the daily capacity
        if(days > D) start = mid+1;
        // mid might be our answer so we cannot set end to mid-1
        else end = mid;
    }
    return end;
};
Enter fullscreen mode Exit fullscreen mode

Discussion (0)