Binary search · Medium
A warehouse sends packages in arrival order. One truck departs per day and has the same capacity every day. Packages cannot be split or reordered; each day takes the next consecutive group. The planner wants the smallest capacity that meets the deadline.
Return the minimum whole-number capacity that ships every package within the allowed number of days.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ weights: integer[], days: integer }
Fields
- weights contains positive integer package weights in shipping order.
- days is the maximum number of departures; using fewer days is allowed.
Output
Return value
- Return one integer capacity. It must fit every package individually and preserve package order.
- Empty input returns 0. A day may remain unused; do not force exactly days nonempty groups.
Constraints
- 0 <= weights.length <= 100000; 1 <= weights[i] <= 1000000000; 1 <= days <= 100000.
- The total weight is at most 100000000000000 and fits in a safe JSON integer.
Examples
Example 1
{
"days": 3,
"weights": [
1,
2,
3,
4,
5
]
}Returns
6Example 2
{
"days": 10,
"weights": [
8,
1,
1
]
}Returns
8Required complexity
O(n log(S + 1)) time and O(1) auxiliary space for total weight S