Filling Bookcase Shelves LeetCode solution in Java

1
class Solution {
2
public int minHeightShelves(int[][] books, int shelfWidth) {
3
int memo[] = new int[books.length];
4
return recur(books, shelfWidth, 0, memo);
5
}
6

7
private int recur(int[][] books, int shelfWidth, int index, int[] memo) {
8

9
if (index == books.length) {
10
return 0;
11
}
12

13
if (memo[index] > 0) {
14
return memo[index];
15
}
16
int ans = Integer.MAX_VALUE;
17
int height = 0;
18
int width = 0;
19

20
for (int i = index; i < books.length; i++) {
21
width += books[i][0];
22

23
if (width > shelfWidth) {
24
break;
25
}
26
height = Math.max(height, books[i][1]);
27
ans = Math.min(ans, height + recur(books, shelfWidth, i + 1, memo));
28
}
29
return memo[index] = ans;
30
}
31
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0