forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackpack-ii(AC).cpp
More file actions
33 lines (31 loc) · 831 Bytes
/
backpack-ii(AC).cpp
File metadata and controls
33 lines (31 loc) · 831 Bytes
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
// O(n * m) time, O(m) space
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param A & V: Given n items with size A[i] and value V[i]
* @return: The maximum value
*/
int backPackII(int m, vector<int> A, vector<int> V) {
vector<int> dp;
int n = A.size();
int i, j;
dp.resize(m + 1, -1);
dp[0] = 0;
for (i = 0; i < n; ++i) {
for (j = m; j >= A[i]; --j) {
if (dp[j - A[i]] < 0) {
continue;
}
dp[j] = max(dp[j], dp[j - A[i]] + V[i]);
}
}
int ans = 0;
for (i = m; i >= 0; --i) {
ans = max(ans, dp[i]);
}
return ans;
}
};