The Filling Bookcase Shelves interview question asks you to arrange a sequence of books on shelves of a fixed width. For each book, you are given its thickness and its height. You must place books in the order they are given. You can start a new shelf at any time, but the total thickness of books on a single shelf cannot exceed the shelfWidth. The height of a shelf is determined by the tallest book on it. Your goal is to minimize the total height of the bookcase (the sum of heights of all shelves).
Companies like Google and Amazon use this Dynamic Programming interview pattern to test your ability to make optimal grouping decisions. It's a variation of the "Partition problem" or "Word Wrap" algorithm. It evaluates if you can identify that the decision of where to split the current shelf depends on the optimal arrangement of the previous books.
The problem is solved using 1D Dynamic Programming.
dp[i] as the minimum height to arrange the first i books.dp[0] = 0.dp[i], try placing the book on a new shelf with some number of preceding books ().
dp[i] = min(dp[j] + max_height_of_books_from_j_to_i) where the sum of thicknesses from to is .dp[n].Books: [[1, 2], [2, 3], [2, 3]], shelfWidth: 4
dp[0] = 0.dp[1]: Only book 1. Height = 2. dp[1] = 2.dp[2]:
dp[1] + 3 = 5.dp[0] + max(2, 3) = 3.dp[2] = 3.dp[3]:
dp[2] + 3 = 6.dp[1] + max(3, 3) = 2 + 3 = 5.dp[3] = 5.This is a "grouping" DP problem. Whenever you need to split a linear sequence into groups to optimize a cost, the dp[i] = min(dp[j] + cost(j, i)) pattern is usually the way to go.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Last Stone Weight II | Medium | Solve | |
| Find the Maximum Length of Valid Subsequence I | Medium | Solve | |
| Maximum Absolute Sum of Any Subarray | Medium | Solve | |
| Maximum Alternating Subsequence Sum | Medium | Solve | |
| Solving Questions With Brainpower | Medium | Solve |