01
Problem Statement
You have weights[i] representing the weight of the i-th package. Ships carry packages in order; each ship has the same capacity cap. We need to ship all packages within days days (at most one ship per day). Return the minimum cap such that all packages can be shipped within days days.
- Lower bound for
capismax(weights)(each package must fit). Upper bound issum(weights)(one ship could take all). We binary search oncap. For a givencap, check if we can ship in<= daysusing a greedy simulation: fill the current ship until adding the next package would exceedcap, then start a new day.
02
Key Observations
- Binary search on the answer:
low = max(weights),high = sum(weights). Formid, definepossible(mid): can we ship all packages in at mostdaysdays with capacitymid? Greedy: iterate packages, accumulate weight; when adding the next would exceedmid, start a new ship (new day). Count days; return true ifdays <= D. - If
possible(mid)is true, any larger capacity also works; so we search for the minimumcapthat works: ifpossible(mid), sethigh = mid(oranswer = mid,high = mid - 1); elselow = mid + 1. Returnlow(or the stored answer).
03
Approach
High-level: Binary search cap in [max(weights), sum(weights)]. For each mid, simulate: need = 1 day, cur = 0; for each weight w: if cur + w > mid then need++, cur = 0; cur += w. If need <= days, high = mid; else low = mid + 1. Return low.
Steps:
low = max(weights),high = sum(weights). Whilelow < high:mid = low + (high - low) / 2. Computeneed(number of days) with capacitymid(greedy). Ifneed <= days,high = mid; elselow = mid + 1.- Return
low.
04
Implementation
Java
public int shipWithinDays(int[] weights, int days) {
int low = 0, high = 0;
for (int w : weights) { low = Math.max(low, w); high += w; }
while (low < high) {
int mid = low + (high - low) / 2;
int need = 1, cur = 0;
for (int w : weights) {
if (cur + w > mid) { need++; cur = 0; }
cur += w;
}
if (need <= days) {
high = mid;
}
else {
low = mid + 1;
}
}
return low;
}05
Test Cases
Example 1
Input
weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Expected
15Explanation
Min capacity 15.
06
Complexity Analysis
- Time: O(n log(sum)).
- Space: O(1).
07
Follow-ups
- Split array largest sum (same idea).