|
| 1 | +/** |
| 2 | + * 1105. Filling Bookcase Shelves |
| 3 | + * https://leetcode.com/problems/filling-bookcase-shelves/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness |
| 7 | + * and height of the ith book. You are also given an integer shelfWidth. |
| 8 | + * |
| 9 | + * We want to place these books in order onto bookcase shelves that have a total width shelfWidth. |
| 10 | + * |
| 11 | + * We choose some of the books to place on this shelf such that the sum of their thickness is less |
| 12 | + * than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the |
| 13 | + * total height of the bookcase has increased by the maximum height of the books we just put down. |
| 14 | + * We repeat this process until there are no more books to place. |
| 15 | + * |
| 16 | + * Note that at each step of the above process, the order of the books we place is the same order |
| 17 | + * as the given sequence of books. |
| 18 | + * |
| 19 | + * For example, if we have an ordered list of 5 books, we might place the first and second book |
| 20 | + * onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the |
| 21 | + * last shelf. |
| 22 | + * |
| 23 | + * Return the minimum possible height that the total bookshelf can be after placing shelves in |
| 24 | + * this manner. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number[][]} books |
| 29 | + * @param {number} shelfWidth |
| 30 | + * @return {number} |
| 31 | + */ |
| 32 | +var minHeightShelves = function(books, shelfWidth) { |
| 33 | + const dp = new Array(books.length + 1).fill(0); |
| 34 | + |
| 35 | + for (let i = 1; i <= books.length; i++) { |
| 36 | + let width = books[i - 1][0]; |
| 37 | + let height = books[i - 1][1]; |
| 38 | + dp[i] = dp[i - 1] + height; |
| 39 | + |
| 40 | + let j = i - 2; |
| 41 | + while (j >= 0 && width + books[j][0] <= shelfWidth) { |
| 42 | + width += books[j][0]; |
| 43 | + height = Math.max(height, books[j][1]); |
| 44 | + dp[i] = Math.min(dp[i], dp[j] + height); |
| 45 | + j--; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return dp[books.length]; |
| 50 | +}; |
0 commit comments