Ctrl K

The Lowest Bookcase

Medium
You need to put books onto the shelves of a bookcase. Book books[i] = [thickness, height]. Every shelf is width wide: the total thickness of the books on one shelf cannot exceed it. The books go in strictly in the given order: the first few books on the top shelf, the next few on the shelf below, and so on. A shelf is as tall as the tallest book on it, and the bookcase is as tall as all its shelves together. Return the smallest possible height of the bookcase.
Example 1
books=[[2, 5], [1, 2], [3, 2], [2, 6]], width=4 → 13

Shelf one: books 0 and 1 (thickness 3, height 5). Shelf two: book 2 (height 2). Shelf three: book 3 (height 6). Total 13. Putting books 1 and 2 together leaves book 0 alone, giving the same total; nothing does better.

Example 2
books=[[1, 4], [1, 4], [1, 4]], width=3 → 4

All three books fit on one shelf of height 4.

Example 3
books=[[3, 1], [1, 9], [3, 1], [1, 1]], width=4 → 10
Constraints
  • 1 ≤ len(books) ≤ 1000
  • 1 ≤ thickness ≤ width ≤ 1000
  • 1 ≤ height ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
books=[[2, 5], [1, 2], [3, 2], [2, 6]], width=4
Expected
13

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.