Sponsored
Sponsored
This approach involves using dynamic programming to decide the optimal cutting of shelves using the given books. Let df[i]
be the minimum height for placing the first i books. For each book i, you consider ending a new shelf at book i but try every starting point from j = i to find the best cut. The key here is to use a nested loop to calculate the minimum height iteratively.
Time Complexity: O(n^2), where n is the number of books.
Space Complexity: O(n), due to the use of extra space for the dp array.
1import java.util.*;
2
3class Solution {
4 public int minHeightShelves(int[][] books, int shelfWidth) {
5 int n = books.length;
6 int[] dp = new int[n + 1];
7 Arrays.fill(dp, Integer.MAX_VALUE);
8 dp[0] = 0;
9 for (int i = 1; i <= n; i++) {
10 int width = 0, height = 0;
11 for (int j = i; j > 0; j--) {
12 width += books[j - 1][0];
13 if (width > shelfWidth) break;
14 height = Math.max(height, books[j - 1][1]);
15 dp[i] = Math.min(dp[i], dp[j - 1] + height);
16 }
17 }
18 return dp[n];
19 }
20}
In this Java solution, we use a dp array to store the minimum heights for the books. The algorithm iteratively adds books to the current shelf, recalculating the shelf height and updating the dp array accordingly.
This strategy uses a recursive backtracking approach augmented with memoization to avoid redundant calculations. By attempting to place books on shelves recursively and caching computed heights, it achieves optimal placement efficiently. This method provides a balance between direct computation and saved results.
Time Complexity: O(n^2), primarily constrained due to state saving over recursion calls
Space Complexity: O(n), requires extra space for memoization.
1
The C code recursively tries to place each book on a new shelf or the current shelf. It uses a memoization array dp
to store computed minimum heights for the subproblems, avoiding recomputation. This recursion explores every possibility and chooses the arrangement yielding the minimum height incrementally.