Minimum height Shelves
XXX. Minimum Height Shelves
Dynamic Programming
Optimization
Problem Statement:
You are given an array books
, where each books[i] = [thicknessi, heighti]
represents the thickness and height of the ith
book. You are also given an integer shelfWidth
representing the maximum width of each shelf.
Place the books in the order given, arranging them in a bookshelf with the minimum height. Return the height of the bookshelf.
Approach:
- Define a dynamic programming array
dp
, wheredp[i]
represents the minimum height of the bookcase containing all books up to and excluding booki
. - Initialize the base cases:
dp[0] = 0
: No books require zero height.dp[1] = books[0][1]
: The height of the first book determines the shelf height.
- Iterate through each book and calculate the minimum height if:
- The book starts on a new shelf.
- Previous books can fit on the same shelf by reducing the remaining width and updating the maximum height of the shelf.
- Return
dp[books.length]
, which contains the minimum height of the bookcase for all books.
Java Implementation:
// Dynamic Programming Approach
public int minHeightShelves(int[][] books, int shelfWidth) {
// dp[i]: minimum height of bookcase containing all books up to and excluding book i
int[] dp = new int[books.length + 1];
// Base cases
dp[0] = 0; // No books require zero height
dp[1] = books[0][1]; // First book determines the shelf height
for (int i = 2; i <= books.length; i++) {
// New shelf built to hold the current book
int remainingShelfWidth = shelfWidth - books[i - 1][0];
int maxHeight = books[i - 1][1];
dp[i] = books[i - 1][1] + dp[i - 1]; // Start a new shelf
int j = i - 1;
// Calculate the height when previous books are added onto the current shelf
while (j > 0 && remainingShelfWidth - books[j - 1][0] >= 0) {
maxHeight = Math.max(maxHeight, books[j - 1][1]); // Update shelf height
remainingShelfWidth -= books[j - 1][0]; // Reduce available width
dp[i] = Math.min(dp[i], maxHeight + dp[j - 1]); // Update dp with minimum height
j--; // Move to the previous book
}
}
return dp[books.length]; // Minimum height of the bookcase for all books
}
Key Insights:
- Dynamic Programming: Use the
dp
array to keep track of the minimum height required for subsets of books. - Sliding Window: By iterating backward, calculate the maximum height of books that fit on the same shelf while ensuring the shelf width constraint is not violated.
- Efficiency: The approach avoids recalculating heights for overlapping subproblems by using dynamic programming.
Complexity Analysis:
Time Complexity: O(n2)
, where n
is the number of books. For each book, we may iterate backward to calculate the optimal height.
Space Complexity: O(n)
, for the dp
array.