Filling Bookcase Shelves

Medium Topics Company Tags

Each entry in books is [thickness, height]. Place every book upright on shelves of width shelfWidth, preserving the given book order. Each shelf holds a consecutive group of books whose total thickness does not exceed its width. The height of a shelf is the tallest book on it, and the bookcase height is the sum of all shelf heights. Return the smallest possible bookcase height.

Example 1:

Filling Bookcase Shelves, example 1: illustration of the example

Input: books = [[1,1],[2,5],[1,5]]
shelfWidth = 3

Output: 6

Explanation: Place the first book alone on a shelf of height 1. Put the last two books together: their total thickness is 3 and their shelf height is 5. The total height is 6. Filling the first shelf with the first two books would instead require height 10.

Example 2:

Filling Bookcase Shelves, example 2: illustration of the example

Input: books = [[2,3],[2,4]]
shelfWidth = 4

Output: 4

Explanation: Both books fit together because their thicknesses add to 4. The shelf height is the taller book's height, 4, which is the total bookcase height.

Example 3:

Filling Bookcase Shelves, example 3: illustration of the example

Input: books = [[2,3],[2,4]]
shelfWidth = 2

Output: 7

Explanation: Each book fills the entire width, so they must occupy separate shelves. Their heights add to 3+4=7.

Constraints:

  • 1 <= books.length <= 1000
  • books[i] == [thickness, height]
  • 1 <= thickness <= shelfWidth <= 1000
  • 1 <= height <= 1000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.