1011. Capacity To Ship Packages Within D Days
Intuition
Complexity
Space Complexity
Time Complexity
Code
// Helper function to calculate the number of days required to ship all packages with given ship capacity
public int daysToShip(int[] packageWeights, int shipCapacity) {
int currentLoad = 0, requiredDays = 0;
for (int weight : packageWeights) {
// If adding current weight exceeds the capacity, ship the load and start a new day
if (currentLoad + weight > shipCapacity) {
currentLoad = 0;
requiredDays++;
}
currentLoad += weight;
}
// Account for the last day's shipment
if (currentLoad > 0) requiredDays++;
return requiredDays;
}
public int shipWithinDays(int[] packageWeights, int maxAllowedDays) {
int minCapacity = 0, maxCapacity = 0, optimalCapacity = 0;
// Initialize search bounds
for (int weight : packageWeights) {
minCapacity = Math.max(minCapacity, weight); // at least the heaviest package
maxCapacity += weight; // at most all weights in one day
}
// Binary search for the minimum sufficient capacity
while (minCapacity <= maxCapacity) {
int midCapacity = (minCapacity + maxCapacity) / 2;
int daysNeeded = daysToShip(packageWeights, midCapacity);
if (daysNeeded <= maxAllowedDays) {
// Capacity is sufficient, try to find a smaller one
optimalCapacity = midCapacity;
maxCapacity = midCapacity - 1;
} else {
// Not enough capacity, try a larger one
minCapacity = midCapacity + 1;
}
}
return optimalCapacity;
}
Last updated