Link: https://leetcode.com/problems/filling-bookcase-shelves/
Solution:
Topics: DP
Intuition
This is a very tricky DP problem, and we know it is DP because there is no greedy approach that can be used to make an optimal local decision. It took me a while to figure out how to structure the recursion but, fundamentally, this is a still a take/skip pattern…or add-to-shelf/start-new-shelf.
The tricky part is figuring out what the recursive function needs in order to compute the result correctly. I think its easiest to view this in terms of current_width, current_height
. Current_width will control our adding-to-shelf logic and current_height is not the total height but rather the height of the current shelf…which is just the height of the tallest book. When we decide to add a new shelf, the current_height will simply be added to the result.
The code is pretty easy to understand, but admittedly the process of getting there is quite tricky unless you are very strong in DP patterns…even the editorial is a train wreak (at least the top-down explanation is).
Implementation
Mnemonic
You have a pile of books. You can either add the book to the current shelf, or build a new shelf with the current book as it’s start.
Review 1
Very fun and tricky DP problem! The above implementation is very nice, but this time around I managed to come up with a very nice 1d DP solution. It will still be the same time complexity, but it saves a bit of space. This solution takes inspiration from backtracking (but without the state change).
Implementation (1d)