Skip to content

Commit 92bcff4

Browse files
committed
Implement filling-bookcase-shelves
name: filling-bookcase-shelves url: https://leetcode.com/problems/filling-bookcase-shelves difficulty: 2 time: 4 ms time-rank: 99.17 % time-complexity: O(N^2) space: 8.2 MB space-rank: 95.22 % space-complexity: O(N) Fixes #167 Signed-off-by: Christopher Friedt <[email protected]>
1 parent 36f3619 commit 92bcff4

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

filling-bookcase-shelves-test.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
#include <gtest/gtest.h>
8+
9+
#include "filling-bookcase-shelves.cpp"
10+
11+
using namespace std;
12+
13+
TEST(FillingBookcaseShelves, 1_1_2_3_2_3_1_1_1_1_1_1_1_2__4) {
14+
vector<vector<int>> books = {{1, 1}, {2, 3}, {2, 3}, {1, 1},
15+
{1, 1}, {1, 1}, {1, 2}};
16+
int shelf_width = 4;
17+
int expected = 6;
18+
EXPECT_EQ(expected, Solution().minHeightShelves(books, shelf_width));
19+
}
20+
21+
TEST(FillingBookcaseShelves, 1_3_2_4_3_2__6) {
22+
vector<vector<int>> books = {{1, 3}, {2, 4}, {3, 2}};
23+
int shelf_width = 6;
24+
int expected = 4;
25+
EXPECT_EQ(expected, Solution().minHeightShelves(books, shelf_width));
26+
}
27+
28+
TEST(FillingBookcaseShelves, 7_3_8_7_2_7_2_5__10) {
29+
vector<vector<int>> books = {{7,3},{8,7},{2,7},{2,5}};
30+
int shelf_width = 10;
31+
int expected = 15;
32+
EXPECT_EQ(expected, Solution().minHeightShelves(books, shelf_width));
33+
}

filling-bookcase-shelves.cpp

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
// clang-format off
8+
// name: filling-bookcase-shelves
9+
// url: https://leetcode.com/problems/filling-bookcase-shelves
10+
// difficulty: 2
11+
// clang-format on
12+
13+
#include <climits>
14+
#include <vector>
15+
16+
using namespace std;
17+
18+
class Solution {
19+
public:
20+
21+
int minHeightShelves(vector<vector<int>> &books, int shelf_width) {
22+
const size_t N = books.size();
23+
auto dp = vector<int>(N + 1, INT_MAX);
24+
dp[0] = 0;
25+
for(size_t i = 0; i < N; ++i) {
26+
for(int j = i, width = 0, height = 0; j >= 0; --j) {
27+
width += books[j][0];
28+
if (width > shelf_width) {
29+
break;
30+
}
31+
height = max(height, books[j][1]);
32+
dp[i + 1] = min(dp[i + 1], dp[j] + height);
33+
}
34+
}
35+
36+
return dp[N];
37+
}
38+
};

0 commit comments

Comments
 (0)