Filling Bookcase Shelves - Problem
Imagine you're organizing a personal library and want to create the most space-efficient bookcase possible! ๐
You have an array of books where books[i] = [thicknessi, heighti] represents the thickness and height of the i-th book. You also have a shelfWidth constraint for each shelf.
The Challenge: Place all books in the given order onto shelves such that:
- Books must be placed in the exact order given (no rearranging!)
- Each shelf can hold books with total thickness โค
shelfWidth - Each shelf's height equals the tallest book on that shelf
- We want to minimize the total height of the bookcase
For example, if we have 5 books, we might place books 1-2 on shelf 1, book 3 on shelf 2, and books 4-5 on shelf 3. The total height would be the sum of the maximum heights from each shelf.
Goal: Return the minimum possible height of the bookcase after optimal shelf arrangement.
Input & Output
example_1.py โ Basic Case
$
Input:
books = [[1,1],[2,3],[2,3],[1,1]], shelf_width = 4
โบ
Output:
6
๐ก Note:
The optimal arrangement is: Shelf 1: books [1,1] and [2,3] with total thickness 3 โค 4, height = max(1,3) = 3. Shelf 2: books [2,3] and [1,1] with total thickness 3 โค 4, height = max(3,1) = 3. Total height = 3 + 3 = 6.
example_2.py โ Single Shelf
$
Input:
books = [[1,3],[2,4],[3,2]], shelf_width = 6
โบ
Output:
4
๐ก Note:
All books can fit on one shelf since total thickness = 1+2+3 = 6 โค 6. The height is max(3,4,2) = 4.
example_3.py โ Each Book on Separate Shelf
$
Input:
books = [[7,3],[8,7],[2,7],[2,5]], shelf_width = 10
โบ
Output:
15
๐ก Note:
Books [7,3] and [2,7] can share a shelf (thickness 9 โค 10, height = max(3,7) = 7). Book [8,7] goes on its own shelf (height = 7). Book [2,5] goes on its own shelf (height = 5). Total = 7 + 7 + 5 = 19. But better: each book on separate shelf gives 3 + 7 + 7 + 5 = 22. Actually optimal is: shelf 1: [7,3], shelf 2: [8,7], shelf 3: [2,7], [2,5] giving 3 + 7 + 7 = 17. Wait, let me recalculate... Optimal: [7,3] alone (height 3), [8,7] and [2,7] together (thickness 10, height 7), [2,5] alone (height 5). Total = 3 + 7 + 5 = 15.
Constraints
- 1 โค books.length โค 1000
- 1 โค thicknessi โค shelf_width โค 1000
- 1 โค heighti โค 1000
- Books must be placed in the given order (no rearranging allowed)
Visualization
Tap to expand
Understanding the Visualization
1
Analyze the problem
Books must stay in order, shelves have width limits, height = tallest book per shelf
2
Consider choices
At each book, decide: start new shelf or continue current shelf?
3
Use dynamic programming
Remember optimal solutions for subproblems to avoid recalculation
4
Build up solution
dp[i] = minimum height for first i books
Key Takeaway
๐ฏ Key Insight: Dynamic programming transforms an exponential brute-force problem into an efficient O(nยฒ) solution by remembering optimal arrangements for subproblems.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code