Binary search and sorting · Problem 3 of 3

Smallest truck that delivers on time

Pattern: Capacity to Ship Packages: Binary Search

mediumNot solved yet

The problem

A delivery company must ship packages (each a positive weight) in the given order, over at most days days. Each day, one truck takes as many of the next packages as fit within its capacity. Packages can't be split, and the order can't change.

Write a function that returns the smallest truck capacity that ships everything within days. There's always at least one package, and days is at least 1.

text
1smallest_capacity([3, 2, 2, 4, 1, 4], 3)  ->  6
2smallest_capacity([1, 2, 3, 1, 1], 4)     ->  3
3smallest_capacity([10, 2], 5)             ->  10
Capacity 6 in three days
3
2
2
4
1
4

Day 1: 3 + 2. Day 2: 2 + 4. Day 3: 1 + 4. Each day fits in 6.

With capacity 6 in the first example, the days are [3, 2], [2, 4], [1, 4]. Capacity 5 would need four days.

Write smallest_capacity(packages, days) in Python or smallestCapacity(packages, days) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 20 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.