Open In App

Capacity To Ship Packages Within D Days

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N positive integers representing the weights of N items and a positive integer D, the task is to find the minimum weight capacity of a boat(say K) to ship all weights within D days such that the order of weights loaded on the ship is in the order of the array elements in arr[] and the total amount of weight loaded by ship each day is K.

Examples:

Input: arr[] = {1, 2, 1}, D = 2
Output: 3
Explanation:
Consider the minimum weight required by the boat as 3, then below is the order of weights such all the weight can be shipped within D(= 2) days:
Day 1: Ship the weights of values 1 and 2 on the first day as the sum of weights 1 + 2 = 3(<= 3).
Day 2: Ship the weights of value 1 on the second day as the sum of weights 1(<= 3).
Considering the minimum weight amount as 3, ships all the weight within D(= 2) days. Therefore, print 3.

Input: arr[] = {9, 8, 10}, D = 3
Output: 10

Check By MAX_Element(mx) in just O(answer-mx):

The_Approach:

    The problem is to find the minimum storage that boat can ship it in D days. So first we find the max_weight that we need to ship in the given array in order to get that minimum weight capacity of a boat than we check by (making sum of subarray upto max_weight and making D part of array if it satisfy then we return true and print the subarray_sum) this process it goes on till (answer-max_weight).

C++




#include <iostream>
#include<bits/stdc++.h>
using namespace std;
 
//function for checking the that sum is minimum weight capacity of a boat
// to ship all weight in d days or not.
bool check(vector<int>&v,int index,int sum,int remain,int n){
       //curr_sum checker fo sub_array.
       int xsum=0;
       //to_check the number of days.
       int cnt=0;
       //here we go for all part that are possible.
       for(int i=index;i<n;i++){
           xsum+=v[i];
           if(xsum>=sum){
               if(xsum==sum)xsum=0;
               else xsum=v[i];
               ++cnt;
           }
            if(n-i==remain-cnt)return 1;
       }
       if(xsum!=0)++cnt;
       return cnt==remain;
}
 
int main() {
    //weights carrying vector.
    vector<int>v{1, 2, 1};
    //number of days.
    int d=2;
    //max_weights need to ship.
    int m=*max_element(v.begin(),v.end());
    //if there is only one days to ship then all
    //the weights need tos ship in just one day.
    if(d==1){
        int sum=0;
        for(auto it:v)sum+=it;
        cout<<sum<<endl;
        return 0;
     }
     //size of vector and int i for traversing.
     int n=v.size();int i=0;
     // infinite loop.
     while(1){
         //function call for checking if m is minimum weight capacity of a boat.
         if(check(v,i,m,d,n)){
              cout<<"Minimum Capacity Of Boat To Ship Weights In "<<d<<" Days Should Be: ";
              cout<<m<<endl;
              return 0;
          }
       ++m;
     }
     cout<<"Minimum Capacity Of Boat To Ship Weights In "<<d<<" Days Should Be: ";
     cout<<m<<endl;
    return 0;
  //this code is contributed by Sanket Gode(sanketgode0).
}


Java




// Java program for the above approach
 
import java.util.*;
 
public class Main {
    public static boolean check(List<Integer> v, int index,
                                int sum, int remain, int n)
    {
        // curr_sum checker for sub_array.
        int xsum = 0;
        // to_check the number of days.
        int cnt = 0;
        // here we go for all parts that are possible.
        for (int i = index; i < n; i++) {
            xsum += v.get(i);
            if (xsum >= sum) {
                if (xsum == sum)
                    xsum = 0;
                else
                    xsum = v.get(i);
                ++cnt;
            }
            if (n - i == remain - cnt)
                return true;
        }
        if (xsum != 0)
            ++cnt;
        return cnt == remain;
    }
 
    public static void main(String[] args)
    {
        // weights carrying vector.
        List<Integer> v = new ArrayList<Integer>();
        v.add(1);
        v.add(2);
        v.add(1);
        // number of days.
        int d = 2;
        // max_weights need to ship.
        int m = Collections.max(v);
        // if there is only one day to ship then all
        // the weights need to be shipped in just one day.
        if (d == 1) {
            int sum = 0;
            for (int i = 0; i < v.size(); i++)
                sum += v.get(i);
            System.out.println(sum);
            return;
        }
        // size of vector and int i for traversing.
        int n = v.size();
        int i = 0;
        // infinite loop.
        while (true) {
            if (check(v, i, m, d, n)) {
                System.out.print(
                    "Minimum Capacity Of Boat To Ship Weights In "
                    + d + " Days Should Be: ");
                System.out.println(m);
                return;
            }
            ++m;
        }
    }
}


Python3




# function for checking the that sum is minimum weight capacity of a boat
# to ship all weight in d days or not.
def check(v, index, sum, remain, n):
    # curr_sum checker fo sub_array.
    xsum = 0
 
    # to_check the number of days.
    cnt = 0
 
    # here we go for all part that are possible.
    for i in range(index, n):
        xsum += v[i]
        if xsum >= sum:
            if xsum == sum:
                xsum = 0
            else:
                xsum = v[i]
            cnt += 1
        if n-i == remain-cnt:
            return 1
    if xsum != 0:
        cnt += 1
    return cnt == remain
 
 
v = [1, 2, 1]
d = 2
 
m = max(v)
 
if d == 1:
    sum = 0
    for it in v:
        sum += it
    print(sum)
else:
    n = len(v)
    i = 0
 
    while True:
        if check(v, i, m, d, n):
            print("Minimum Capacity Of Boat To Ship Weights In " + str(d) + " Days Should Be: " + str(m))
            break
        m += 1


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class Program
{
    public static bool check(List<int> v, int index,
                             int sum, int remain, int n)
    {
        // curr_sum checker for sub_array.
        int xsum = 0;
       
        // to_check the number of days.
        int cnt = 0;
        // here we go for all parts that are possible.
        for (int i = index; i < n; i++)
        {
            xsum += v[i];
            if (xsum >= sum)
            {
                if (xsum == sum)
                    xsum = 0;
                else
                    xsum = v[i];
                ++cnt;
            }
            if (n - i == remain - cnt)
                return true;
        }
        if (xsum != 0)
            ++cnt;
        return cnt == remain;
    }
 
    public static void Main(string[] args)
    {
        // weights carrying vector.
        List<int> v = new List<int>();
        v.Add(1);
        v.Add(2);
        v.Add(1);
       
        // number of days.
        int d = 2;
       
        // max_weights need to ship.
        int m = v.Max();
       
        // if there is only one day to ship then all
        // the weights need to be shipped in just one day.
        if (d == 1)
        {
            int sum = 0;
            for (int j = 0; j < v.Count; j++)
                sum += v[j];
            Console.WriteLine(sum);
            return;
        }
       
        // size of vector and int i for traversing.
        int n = v.Count;
        int i = 0;
       
        // infinite loop.
        while (true)
        {
            if (check(v, i, m, d, n))
            {
                Console.Write(
                    "Minimum Capacity Of Boat To Ship Weights In "
                    + d + " Days Should Be: ");
                Console.WriteLine(m);
                return;
            }
            ++m;
        }
    }
}


Javascript




// function for checking the that sum is minimum weight capacity of a boat
// to ship all weight in d days or not.
function check(v,index,sum,remain,n)
{
 
       // curr_sum checker fo sub_array.
       let xsum=0;
        
       // to_check the number of days.
       let cnt=0;
         
       // here we go for all part that are possible.
       for(let i = index; i < n; i++)
       {
           xsum += v[i];
           if(xsum >= sum){
               if(xsum == sum)xsum=0;
               else xsum = v[i];
               ++cnt;
           }
            if(n-i == remain-cnt)return 1;
       }
       if(xsum != 0)++cnt;
       return cnt == remain;
}
 
let v = [1, 2, 1];
let d = 2;
 
let m = Math.max(...v);
 
if(d==1){
    let sum=0;
    for(let it of v) sum+=it;
    console.log(sum);
    return 0;
}
 
let n=v.length; let i=0;
 
while(1){
    if(check(v,i,m,d,n)){
        console.log("Minimum Capacity Of Boat To Ship Weights In " + d + " Days Should Be: " + m);
        return 0;
    }
   ++m;
}
console.log("Minimum Capacity Of Boat To Ship Weights In " + d + " Days Should Be: " + m);


Output

Minimum Capacity Of Boat To Ship Weights In 2 Days Should Be: 3

Complexity Analysis:

  Time Complexity:O(answer-mx)*O(n), answer is result and mx is max_element of array.

  Space Complexity:O(1).

Approach: The given problem can be solved by using the Greedy Technique and Binary Search. The monotonicity of the problem can be observed that if all packages can be successfully shipped within D days with capacity K, then definitely they can be shipped with any capacity larger than K. Follow the steps below to solve the problem:

  • Initialize a variable, say ans as -1 to store the resultant minimum capacity of the boat required.
  • Initialize two variables, say s and e with the maximum element in the given array and the total sum of the array respectively which denotes the lower and upper bounds of the search space.
  • Iterate until the value of s is less than or equals to e, and perform the following steps:
    • Initialize a variable, say mid as (s + e)/2.
    • Check if it is possible to ship all the packages within D days when the maximum capacity allowed is mid. If found to be true, then update the value of ans to mid and the value of e to (mid – 1).
    • Otherwise, update the value of s to (mid + 1).
  • After completing the above steps, print the value of ans as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the weights can be delivered in D
// days or not
bool isValid(int weight[], int n, int D, int mx)
{
    // Stores the count of days required to ship all the
    // weights if the maximum capacity is mx
    int st = 1;
    int sum = 0;
 
    // Traverse all the weights
    for (int i = 0; i < n; i++) {
        sum += weight[i];
 
        // If total weight is more than the maximum capacity
        if (sum > mx) {
            st++;
            sum = weight[i];
        }
 
        // If days are more than D, then return false
        if (st > D)
            return false;
    }
 
    // Return true for the days < D
    return true;
}
 
// Function to find the least weight capacity of a boat to
// ship all the weights within D days
void shipWithinDays(int weight[], int D, int n)
{
    // Stores the total weights to be shipped
    int sum = 0;
 
    // Find the sum of weights
    for (int i = 0; i < n; i++)
        sum += weight[i];
 
    // Stores the maximum weight in the array that has to be
    // shipped
    int s = weight[0];
    for (int i = 1; i < n; i++)
        s = max(s, weight[i]);
 
    // Store the ending value for the search space
    int e = sum;
 
    // Store the required result
    int res = -1;
 
    // Perform binary search
    while (s <= e) {
 
        // Store the middle value
        int mid = s + (e - s) / 2;
 
        // If mid can be shipped, then update the result and
        // end value of the search space
        if (isValid(weight, n, D, mid)) {
            res = mid;
            e = mid - 1;
        }
 
        // Search for minimum value in the right part
        else
            s = mid + 1;
    }
 
    // Print the result
    cout << res;
}
 
// Driver Code
int main()
{
    int weight[] = { 9, 8, 10 };
    int D = 3;
    int N = sizeof(weight) / sizeof(weight[0]);
    shipWithinDays(weight, D, N);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program for the above approach
 
#include <stdbool.h>
#include <stdio.h>
 
// Find maximum between two numbers.
int max(int num1, int num2)
{
    return (num1 > num2) ? num1 : num2;
}
 
// Function to check if the weights can be delivered in D
// days or not
bool isValid(int weight[], int n, int D, int mx)
{
    // Stores the count of days required to ship all the
    // weights if the maximum capacity is mx
    int st = 1;
    int sum = 0;
 
    // Traverse all the weights
    for (int i = 0; i < n; i++) {
        sum += weight[i];
 
        // If total weight is more than the maximum capacity
        if (sum > mx) {
            st++;
            sum = weight[i];
        }
 
        // If days are more than D, then return false
        if (st > D)
            return false;
    }
 
    // Return true for the days < D
    return true;
}
 
// Function to find the least weight capacity of a boat to
// ship all the weights within D days
void shipWithinDays(int weight[], int D, int n)
{
    // Stores the total weights to be shipped
    int sum = 0;
 
    // Find the sum of weights
    for (int i = 0; i < n; i++)
        sum += weight[i];
 
    // Stores the maximum weight in the array that has to be
    // shipped
    int s = weight[0];
    for (int i = 1; i < n; i++)
        s = max(s, weight[i]);
 
    // Store the ending value for the search space
    int e = sum;
 
    // Store the required result
    int res = -1;
 
    // Perform binary search
    while (s <= e) {
 
        // Store the middle value
        int mid = s + (e - s) / 2;
 
        // If mid can be shipped, then update the result and
        // end value of the search space
        if (isValid(weight, n, D, mid)) {
            res = mid;
            e = mid - 1;
        }
 
        // Search for minimum value in the right part
        else
            s = mid + 1;
    }
 
    // Print the result
    printf("%d", res);
}
 
// Driver Code
int main()
{
    int weight[] = { 9, 8, 10 };
    int D = 3;
    int N = sizeof(weight) / sizeof(weight[0]);
    shipWithinDays(weight, D, N);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to check if the weights can be delivered in
    // D days or not
    static boolean isValid(int[] weight, int n, int D,
                           int mx)
    {
 
        // Stores the count of days required to ship all the
        // weights if the maximum capacity is mx
        int st = 1;
        int sum = 0;
 
        // Traverse all the weights
        for (int i = 0; i < n; i++) {
            sum += weight[i];
 
            // If total weight is more than the maximum
            // capacity
            if (sum > mx) {
                st++;
                sum = weight[i];
            }
 
            // If days are more than D, then return false
            if (st > D)
                return false;
        }
 
        // Return true for the days < D
        return true;
    }
 
    // Function to find the least weight capacity of a boat
    // to ship all the weights within D days
    static void shipWithinDays(int[] weight, int D, int n)
    {
 
        // Stores the total weights to be shipped
        int sum = 0;
 
        // Find the sum of weights
        for (int i = 0; i < n; i++)
            sum += weight[i];
 
        // Stores the maximum weight in the array that has
        // to be shipped
        int s = weight[0];
        for (int i = 1; i < n; i++) {
            s = Math.max(s, weight[i]);
        }
 
        // Store the ending value for the search space
        int e = sum;
 
        // Store the required result
        int res = -1;
 
        // Perform binary search
        while (s <= e) {
 
            // Store the middle value
            int mid = s + (e - s) / 2;
 
            // If mid can be shipped, then update the result
            // and end value of the search space
            if (isValid(weight, n, D, mid)) {
                res = mid;
                e = mid - 1;
            }
 
            // Search for minimum value in the right part
            else
                s = mid + 1;
        }
 
        // Print the result
        System.out.println(res);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] weight = { 9, 8, 10 };
        int D = 3;
        int N = weight.length;
        shipWithinDays(weight, D, N);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 program for the above approach
 
# Function to check if the weights
# can be delivered in D days or not
def isValid(weight, n, D, mx):
     
    # Stores the count of days required
    # to ship all the weights if the
    # maximum capacity is mx
    st = 1
    sum = 0
 
    # Traverse all the weights
    for i in range(n):
        sum += weight[i]
 
        # If total weight is more than
        # the maximum capacity
        if (sum > mx):
            st += 1
            sum = weight[i]
 
        # If days are more than D,
        # then return false
        if (st > D):
            return False
 
    # Return true for the days < D
    return True
 
# Function to find the least weight
# capacity of a boat to ship all the
# weights within D days
def shipWithinDays(weight, D, n):
     
    # Stores the total weights to
    # be shipped
    sum = 0
 
    # Find the sum of weights
    for i in range(n):
        sum += weight[i]
 
    # Stores the maximum weight in the
    # array that has to be shipped
    s = weight[0]
    for i in range(1, n):
        s = max(s, weight[i])
 
    # Store the ending value for
    # the search space
    e = sum
 
    # Store the required result
    res = -1
 
    # Perform binary search
    while (s <= e):
         
        # Store the middle value
        mid = s + (e - s) // 2
 
        # If mid can be shipped, then
        # update the result and end
        # value of the search space
        if (isValid(weight, n, D, mid)):
            res = mid
            e = mid - 1
 
        # Search for minimum value
        # in the right part
        else:
            s = mid + 1
 
    # Print the result
    print(res)
 
# Driver Code
if __name__ == '__main__':
     
    weight = [ 9, 8, 10 ]
    D = 3
    N = len(weight)
     
    shipWithinDays(weight, D, N)
 
# This code is contributed by ipg2016107


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if the weights
// can be delivered in D days or not
static bool isValid(int[] weight, int n,
                    int D, int mx)
{
     
    // Stores the count of days required
    // to ship all the weights if the
    // maximum capacity is mx
    int st = 1;
    int sum = 0;
 
    // Traverse all the weights
    for(int i = 0; i < n; i++)
    {
        sum += weight[i];
 
        // If total weight is more than
        // the maximum capacity
        if (sum > mx)
        {
            st++;
            sum = weight[i];
        }
 
        // If days are more than D,
        // then return false
        if (st > D)
            return false;
    }
 
    // Return true for the days < D
    return true;
}
 
// Function to find the least weight
// capacity of a boat to ship all the
// weights within D days
static void shipWithinDays(int[] weight, int D, int n)
{
     
    // Stores the total weights to
    // be shipped
    int sum = 0;
 
    // Find the sum of weights
    for(int i = 0; i < n; i++)
        sum += weight[i];
 
    // Stores the maximum weight in the
    // array that has to be shipped
    int s = weight[0];
    for(int i = 1; i < n; i++)
    {
        s = Math.Max(s, weight[i]);
    }
 
    // Store the ending value for
    // the search space
    int e = sum;
 
    // Store the required result
    int res = -1;
 
    // Perform binary search
    while (s <= e)
    {
         
        // Store the middle value
        int mid = s + (e - s) / 2;
 
        // If mid can be shipped, then
        // update the result and end
        // value of the search space
        if (isValid(weight, n, D, mid))
        {
            res = mid;
            e = mid - 1;
        }
 
        // Search for minimum value
        // in the right part
        else
            s = mid + 1;
    }
 
    // Print the result
    Console.WriteLine(res);
}
 
// Driver Code
public static void Main()
{
    int[] weight = { 9, 8, 10 };
    int D = 3;
    int N = weight.Length;
     
    shipWithinDays(weight, D, N);
}
}
 
// This code is contributed by ukasp


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to check if the weights
// can be delivered in D days or not
function isValid(weight, n,
                       D, mx)
{
      
    // Stores the count of days required
    // to ship all the weights if the
    // maximum capacity is mx
    let st = 1;
    let sum = 0;
  
    // Traverse all the weights
    for(let i = 0; i < n; i++)
    {
        sum += weight[i];
  
        // If total weight is more than
        // the maximum capacity
        if (sum > mx)
        {
            st++;
            sum = weight[i];
        }
  
        // If days are more than D,
        // then return false
        if (st > D)
            return false;
    }
  
    // Return true for the days < D
    return true;
}
  
// Function to find the least weight
// capacity of a boat to ship all the
// weights within D days
function shipWithinDays(weight, D, n)
{
      
    // Stores the total weights to
    // be shipped
    let sum = 0;
  
    // Find the sum of weights
    for(let i = 0; i < n; i++)
        sum += weight[i];
  
    // Stores the maximum weight in the
    // array that has to be shipped
    let s = weight[0];
    for(let i = 1; i < n; i++)
    {
        s = Math.max(s, weight[i]);
    }
  
    // Store the ending value for
    // the search space
    let e = sum;
  
    // Store the required result
    let res = -1;
  
    // Perform binary search
    while (s <= e)
    {
          
        // Store the middle value
        let mid = s + Math.floor((e - s) / 2);
  
        // If mid can be shipped, then
        // update the result and end
        // value of the search space
        if (isValid(weight, n, D, mid))
        {
            res = mid;
            e = mid - 1;
        }
  
        // Search for minimum value
        // in the right part
        else
            s = mid + 1;
    }
  
    // Print the result
    document.write(res);
}
 
// Driver Code
 
    let weight = [ 9, 8, 10 ];
    let D = 3;
    let N = weight.length;
      
    shipWithinDays(weight, D, N);
 
</script>


Output

10

Time Complexity: O(N*log(S – M)), where S is the sum of the array elements and M is the maximum element of the array.
Auxiliary Space: O(1)



Last Updated : 01 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads