Skip to content

Commit fa312f3

Browse files
Add minHeightShelves code
1 parent fd0f4b7 commit fa312f3

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Explanation:
2+
The variable f[i] denotes the least height necessary to accommodate the first i books on the shelves.
3+
4+
We begin with a vacant shelf, where the height f[0] is set to 0, as having no books results in no height requirement.
5+
6+
For each book i, the approach evaluates whether to place it on the same shelf as the preceding books or to initiate a new shelf. It systematically assesses if the addition of the current book to the existing shelf would surpass the shelf's width. If it does not, the height of the shelf is determined by the tallest book already present on that shelf. The value of f[i] is then updated to reflect the lesser of its current value and the height achieved by including the book on the current shelf.
7+
8+
Should the inclusion of a book cause the current shelf to exceed its maximum width, the process halts, prompting the start of a new shelf.
9+
10+
This methodology guarantees that the overall height of the bookshelves is minimized while adhering to the width limitations of each shelf.
11+
12+
Complexity
13+
Time complexity:
14+
O(n**2)
15+
16+
Space complexity:
17+
O(n)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution
2+
{
3+
public:
4+
int minHeightShelves(vector<vector<int>> &books, int shelfWidth)
5+
{
6+
int n = books.size();
7+
int f[n + 1];
8+
f[0] = 0;
9+
for (int i = 1; i <= n; ++i)
10+
{
11+
int w = books[i - 1][0], h = books[i - 1][1];
12+
f[i] = f[i - 1] + h;
13+
for (int j = i - 1; j > 0; --j)
14+
{
15+
w += books[j - 1][0];
16+
if (w > shelfWidth)
17+
{
18+
break;
19+
}
20+
h = max(h, books[j - 1][1]);
21+
f[i] = min(f[i], f[j - 1] + h);
22+
}
23+
}
24+
return f[n];
25+
}
26+
};

0 commit comments

Comments
 (0)