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
- Binary search on ship capacity
- Minimum capacity = largest package (must fit)
- Maximum capacity = sum of all (ship everything in 1 day)
- For given capacity, greedily count days needed
Related Data Structures & Algorithms exercises
- Practice Find Minimum in Rotated Sorted Array in Java
- Practice Koko Eating Bananas in Java
- Practice Subsets (Power Set) in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler