1105. Filling Bookcase Shelves #176
-
You are given an array We want to place these books in order onto bookcase shelves that have a total width We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books.
Return the minimum possible height that the total bookshelf can be after placing shelves in this manner. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1105. Filling Bookcase Shelves <?php
function minHeightShelves($books, $shelfWidth) {
$n = count($books);
$dp = array_fill(0, $n + 1, PHP_INT_MAX);
$dp[0] = 0;
for ($i = 1; $i <= $n; $i++) {
$width = 0;
$height = 0;
for ($j = $i; $j > 0; $j--) {
$width += $books[$j - 1][0];
if ($width > $shelfWidth) {
break;
}
$height = max($height, $books[$j - 1][1]);
$dp[$i] = min($dp[$i], $dp[$j - 1] + $height);
}
}
return $dp[$n];
}
// Example usage:
$books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]];
$shelfWidth = 4;
echo minHeightShelves($books, $shelfWidth); // Output: 6
$books = [[1,3],[2,4],[3,2]];
$shelfWidth = 6;
echo minHeightShelves($books, $shelfWidth); // Output: 4
?> Explanation:
This solution effectively uses dynamic programming to keep track of the minimum possible height of the bookshelf as books are placed, ensuring the constraints are respected. Contact Links If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me! If you want more helpful content like this, feel free to follow me: |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
dp
array wheredp[0] = 0
(no books, no height).i
, try to place it on the current shelf or start a new shelf. Updatedp[i]
with the minimum possible height after placing booki
.shelfWidth
. Update thedp
array accordingly.Let's implement this solution in PHP: 1105. Filling Bookcase Shelves