Skip to content

Commit ab9fffa

Browse files
committed
Runtime: 0 ms (Top 100.0%) | Memory: 42.30 MB (Top 39.5%)
1 parent f58a4b9 commit ab9fffa

File tree

1 file changed

+28
-28
lines changed

1 file changed

+28
-28
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
1+
// Runtime: 0 ms (Top 100.0%) | Memory: 42.30 MB (Top 39.5%)
12

23
class Solution {
3-
int[][] books;
4-
int shefWidth;
5-
6-
Map<String, Integer> memo = new HashMap();
7-
8-
public int findMinHeight(int curr, int maxHeight, int wRem) {
9-
String key = curr + ":" + wRem ;
10-
11-
if(memo.containsKey(key)) return memo.get(key);
12-
13-
14-
if(curr == books.length ) return maxHeight;
15-
int[] currBook = books[curr];
16-
17-
memo.put( key, currBook[0] <= wRem ? Math.min( maxHeight + findMinHeight(curr + 1, currBook[1], shefWidth - currBook[0]) , // new shelf
18-
findMinHeight(curr + 1, Math.max(maxHeight, currBook[1]),wRem - currBook[0] )) // same shelf
19-
: maxHeight + findMinHeight(curr + 1, currBook[1], shefWidth - currBook[0])
20-
); // new shelf
21-
22-
return memo.get(key);
23-
}
24-
25-
264
public int minHeightShelves(int[][] books, int shelfWidth) {
27-
this.books = books;
28-
this.shefWidth = shelfWidth;
29-
return findMinHeight(0, 0, shelfWidth);
5+
int memo[] = new int[books.length];
6+
return recur(books, shelfWidth, 0, memo);
7+
}
8+
9+
private int recur(int[][] books, int shelfWidth, int index, int[] memo) {
10+
11+
if (index == books.length) {
12+
return 0;
13+
}
14+
15+
if (memo[index] > 0) {
16+
return memo[index];
17+
}
18+
int ans = Integer.MAX_VALUE;
19+
int height = 0;
20+
int width = 0;
21+
22+
for (int i = index; i < books.length; i++) {
23+
width += books[i][0];
24+
25+
if (width > shelfWidth) {
26+
break;
27+
}
28+
height = Math.max(height, books[i][1]);
29+
ans = Math.min(ans, height + recur(books, shelfWidth, i + 1, memo));
30+
}
31+
return memo[index] = ans;
3032
}
3133
}
32-
33-

0 commit comments

Comments
 (0)