medium +30 pts

Capacity to Ship Packages

Find the minimum ship capacity to deliver all packages within D days.

You are given an array `weights` where `weights[i]` is the weight of the i-th package, and an integer `days`. Packages must be shipped in the given order. Each day, you load packages onto a ship with a maximum capacity `C`. You can load any number of packages as long as their total weight does not exceed `C`, and you cannot split a package across days. The ship can make one trip per day. Write a function `ship_within_days(weights, days)` that returns the minimum integer capacity `C` such that all packages can be shipped within `days` days. For example, if `weights = [3, 2, 2, 4, 1, 4]` and `days = 3`, the minimum capacity is `6`. One way to ship: Day 1: [3, 2], Day 2: [2, 4], Day 3: [1, 4]. Constraints: - `1 <= len(weights) <= 50000` - `1 <= weights[i] <= 500` - `1 <= days <= len(weights)` Your implementation must run in O(n log S) time where S is the sum of weights.

Constraints

1 ≤ len(weights) ≤ 50000, 1 ≤ weights[i] ≤ 500, 1 ≤ days ≤ len(weights). The answer is at least max(weights) and at most sum(weights).

Example

```python
>>> ship_within_days([1,2,3,4,5,6,7,8,9,10], 5)
15
>>> ship_within_days([3,2,2,4,1,4], 3)
6
>>> ship_within_days([1,2,3,1,1], 4)
3
```
30 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

For a given capacity, simulate the shipping process greedily to count how many days are needed.
The minimum possible capacity is at least max(weights), and the maximum is sum(weights).
Use binary search on the capacity range, checking if a capacity can ship all packages within `days`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.