-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmaximum-weight-in-two-bags.cpp
More file actions
58 lines (55 loc) · 1.6 KB
/
maximum-weight-in-two-bags.cpp
File metadata and controls
58 lines (55 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Time: O(n * w1 * w2)
// Space: O(w1 * w2)
// dp, bitset
class Solution {
public:
int maxWeight(vector<int>& weights, int w1, int w2) {
static const int MAX_W = 300;
vector<bitset<MAX_W + 1>> dp(w1 + 1), new_dp(w1 + 1);
dp[0][0] = 1;
for (const auto& w : weights) {
for (int i = 0; i <= w1; ++i) {
new_dp[i] = dp[i] | (i - w >= 0 ? dp[i - w] : 0) | (dp[i] << w);
}
swap(dp, new_dp);
}
int result = 0;
for (int i = 0; i <= w1; ++i) {
for (int j = w2; j >= 0; --j) {
if (dp[i][j]) {
result = max(result, i + j);
break;
}
}
}
return result;
}
};
// Time: O(n * w1 * w2)
// Space: O(w1 * w2)
// dp
class Solution2 {
public:
int maxWeight(vector<int>& weights, int w1, int w2) {
vector<vector<bool>> dp(w1 + 1, vector<bool>(w2 + 1)), new_dp(w1 + 1, vector<bool>(w2 + 1));
dp[0][0] = true;
for (const auto& w : weights) {
for (int i = 0; i <= w1; ++i) {
for (int j = 0; j <= w2; ++j) {
new_dp[i][j] = dp[i][j] || (i - w >= 0 && dp[i - w][j]) || (j - w >= 0 && dp[i][j - w]);
}
}
swap(dp, new_dp);
}
int result = 0;
for (int i = 0; i <= w1; ++i) {
for (int j = w2; j >= 0; --j) {
if (dp[i][j]) {
result = max(result, i + j);
break;
}
}
}
return result;
}
};