|
| 1 | +// Runtime: 0 ms (Top 100.0%) | Memory: 42.30 MB (Top 39.5%) |
1 | 2 |
|
2 | 3 | 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 |
| - |
26 | 4 | 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; |
30 | 32 | }
|
31 | 33 | }
|
32 |
| - |
33 |
| - |
0 commit comments