841. Bookcase Filling
A librarian must arrange a stack of books on shelves without ever changing their order. Each entry books[i] is [thickness, height], and every shelf has an inner width of width. Starting with the first book, the librarian fills a shelf with consecutive books as long as their total thickness does not exceed width, then moves up to a new shelf.
The height of a shelf is the tallest book on it, and the bookcase height is the sum of the shelf heights. Choose where to start each new shelf so that this sum is minimal and return it. A book thicker than width is still accepted: it occupies a shelf entirely on its own.
Aim for time O(n * s) where s is the largest number of books on one shelf, and space O(n).
Example 1
- Input:
- books = [[3,5],[2,8],[4,3],[5,6],[1,9]], width = 7
- Output:
- 20
- Explanation:
Shelving [3,5]+[2,8], then [4,3], then [5,6]+[1,9] gives shelf heights 8, 3 and 9, a total of 20.
Example 2
- Input:
- books = [[12,4],[3,6],[2,5]], width = 10
- Output:
- 10
- Explanation:
The first book is thicker than the shelf so it stands alone (height 4); the other two share a shelf of height 6, giving 10.
Constraints
1 ≤ books.length ≤ 1000
1 ≤ books[i][0], books[i][1] ≤ 1000
1 ≤ width ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms
Expected complexity
- Time
- O(n * s)
- Space
- O(n)