Capacity To Ship Packages in Java: Explanation & Practice

Minimum ship capacity to ship all in D days

Problem summary

Given package weights and D days, find the minimum ship capacity to ship all packages in order within D days.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int days = 5;
        
        // Binary search on capacity
        // Min = max weight (must fit largest), Max = sum of all
        // For each capacity, count days needed
        // Print: Min capacity: 15
    }
}

Expected output and test cases

  • [1-10], days=5
    Min capacity: 15
  • [3,2,2,4,1,4], days=3
    Min capacity: 6
  • [1,2,3,1,1], days=4
    Min capacity: 3

Hints

  1. Binary search on ship capacity
  2. Minimum capacity = largest package (must fit)
  3. Maximum capacity = sum of all (ship everything in 1 day)
  4. For given capacity, greedily count days needed

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler