#1105
Filling Bookcase Shelves
MediumArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses dynamic programming to store the minimum height needed for each book index. By building on previously computed results, we avoid redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array where dp[i] represents the minimum height of the bookshelf for the first i books.
- 2Step 2: Iterate through each book and for each book, check all previous books to see if they can fit on the same shelf.
- 3Step 3: Update the dp array with the minimum height found by considering the maximum height of the current shelf.
solution.py12 lines
1def minHeightShelves(books, shelfWidth):
2 dp = [0] * (len(books) + 1)
3 for i in range(1, len(books) + 1):
4 total_thickness = 0
5 max_height = 0
6 for j in range(i - 1, -1, -1):
7 total_thickness += books[j][0]
8 if total_thickness > shelfWidth:
9 break
10 max_height = max(max_height, books[j][1])
11 dp[i] = min(dp[i], dp[j] + max_height)
12 return dp[len(books)]ℹ
Complexity note: The time complexity remains O(n²) due to the nested loop, but we save results in dp, reducing redundant calculations.
- 1Dynamic programming helps avoid recalculating heights for previously considered books.
- 2Understanding the constraints of shelfWidth is crucial for optimizing book placement.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.