Bookshelf
InterviewTime limit1sMemory limit128 MB
Partition the books in order into shelves whose widths sum to at most L, minimizing the total of each shelf's maximum height.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Array, Prefix sum, Two pointers
- Solved
- No attempts yet
Problem
When Farmer John isn't milking cows, stacking haybales, lining up his cows, or building fences, he enjoys sitting down with a good book. Over the years he has collected books (), and he wants to build a new set of bookshelves to hold them all.
Each book has a width and a height . The books must be placed onto the shelves in the given order: the first shelf holds books for some , the second shelf starts with book , and so on. The total width of the books on any single shelf may be at most (). The height of a shelf equals the height of the tallest book on it, and because the shelves are stacked vertically, the height of the whole bookcase is the sum of the heights of all the shelves.
Compute the minimum possible height of the entire bookcase.
Input
- Line 1: two space-separated integers and .
- Lines 2 to : line contains two space-separated integers, the height and the width of book (, ).
Output
- Print the minimum possible total height of the bookcase on a single line.
Hint
Input Details
There are 5 books, and each shelf may hold books whose total width is at most .
Output Details
The books are placed on 3 shelves: the first holds only book 1 (height 5, width 7), the second holds books (height 13, total width 9), and the third holds book 5 (height 3, width 8).