Problem 347033 · medium · Level 03 Linear Management & Searching

Smallest Truck for a Fixed Number of Trips

binary search on the answer · greedy

Parcels must be delivered in the given order; weights[i] is the weight of parcel i. A truck with capacity c loads consecutive parcels until the next one would exceed c, then makes a trip. Return the smallest integer capacity that delivers everything in at most trips trips.

Examples

Input:  weights = [4, 8, 2, 6, 5, 3, 7], trips = 3
Output: 13
Explanation: loads [4, 8], [2, 6, 5], [3, 7]; with capacity 12 four trips are needed.

Input:  weights = [9, 1, 1, 9], trips = 2
Output: 10

Input:  weights = [2, 3, 2, 3, 2], trips = 5
Output: 3

Constraints

  • 1 <= len(weights) <= 5 * 10**4, 1 <= trips <= len(weights)
  • 1 <= weights[i] <= 500
  • Required time: O(n log(sum(weights))).

Goals

  • Choose the correct lower and upper bounds for the answer range
  • Simulate greedy loading as the feasibility check
Starting Python…