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#include <vector>
#include <limits>
using namespace std;
class Solution {
int dfs(vector<vector<int>> & books, int shelfWidth, int pos, vector<int> & dp) {
if (pos == books.size()) return 0;
if (dp[pos] != -1) return dp[pos];
int width = 0, height = 0, minHeight = INT_MAX;
for (int i = pos; i < books.size(); i++) {
width += books[i][0];
if (width > shelfWidth) break;
height = max(height, books[i][1]);
minHeight = min(minHeight, height + dfs(books, shelfWidth, i + 1, dp));
}
dp[pos] = minHeight;
return minHeight;
}
public:
int minHeightShelves(vector<math>> books, int shelfWidth) {
vector<int> dp(books.size(), -1);
return dfs(books, shelfWidth, 0, dp);
}
};
The C++ version uses a recursive helper function dfs
to try placing books starting from the current position, memoizing results to avoid recalculating overlaps. The function optimally decides the next step by considering when placing on a new shelf might be more beneficial than continuing on the current one.