Skip to content

Commit b9f60c2

Browse files
Create 1105-filling-bookcase-shelves.java
1 parent cff997a commit b9f60c2

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public int minHeightShelves(int[][] books, int shelfWidth) {
3+
Map<Integer, Integer> cache = new HashMap<>();
4+
5+
return helper(books, shelfWidth, 0, cache);
6+
}
7+
private int helper(int[][] books, int shelfWidth, int i, Map<Integer, Integer> cache) {
8+
if (i == books.length) {
9+
return 0;
10+
}
11+
if (cache.containsKey(i)) {
12+
return cache.get(i);
13+
}
14+
15+
int curWidth = shelfWidth;
16+
int maxHeight = 0;
17+
int result = Integer.MAX_VALUE;
18+
19+
for (int j = i; j < books.length; j++) {
20+
int width = books[j][0];
21+
int height = books[j][1];
22+
if (curWidth < width) {
23+
break;
24+
}
25+
curWidth -= width;
26+
maxHeight = Math.max(maxHeight, height);
27+
result = Math.min(result, helper(books, shelfWidth, j + 1, cache) + maxHeight);
28+
}
29+
30+
cache.put(i, result);
31+
return result;
32+
}
33+
}

0 commit comments

Comments
 (0)