Backpack II
Description
Given n items with size Ai and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack?
Notice You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.
Example Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 9.
Challenge
O(n x m) memory is acceptable,
can you do it in O(m) memory?
Link
Method
- x
- x
Example
- 1
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 */ // Version 1, O(n^2) S(n^2) int backPackII(int m, vector<int> A, vector<int> V) { // write your code here if (A.empty() || V.empty() || A.size() != V.size() || m <= 0) { return 0; } int lena = A.size(); vector<vector<int>> dp(lena + 1, vector<int>(m + 1, -1)); dp[0][0] = 0; for (int i = 0; i < lena; ++i) { for (int j = 0; j < m + 1; ++j) { dp[i+1][j] = dp[i][j]; // i means the number of size we selected // j means the volume of current pack // dp[i][j-A[i]] means we want to use A[i] in here // the rest volume j-A[i] has matched size with value if (j >= A[i] && dp[i][j-A[i]] > -1) { dp[i+1][j] = max(dp[i][j], dp[i][j-A[i]] + V[i]); } } } int maxval = 0; for (int i = m; i >= 0; --i) { if (dp[lena][i] > 0) { maxval = max(maxval, dp[lena][i]); } } return maxval; } // Version 2, O(n^2) S(n) int backPackII(int m, vector<int> A, vector<int> V) { if (A.empty() || V.empty() || A.size() != V.size() || m <= 0) { return 0; } int lena = A.size(); vector<int> dp(m + 1, 0); for (int i = 0; i < lena; ++i) { for (int j = m; j >= A[i]; --j) { dp[j] = max(dp[j], dp[j-A[i]] + V[i]); } } return dp[m]; } };
Similar problems
x
Tags
x