Givenn_kind of items with size Aiand value Vi(each item has an infinite number available
) 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.
Have you met this question in a real interview?
Yes
Example
Given 4 items with size[2, 3, 5, 7]
and value[1, 5, 2, 4]
, and a backpack with size10
. The maximum value is15
.
can optimize j from A[i - 1]
class Solution {
public:
/**
* @param A an integer array
* @param V an integer array
* @param m an integer
* @return an array
*/
int backPackIII(vector<int>& A, vector<int>& V, int m) {
// Write your code here
int n = A.size();
vector<int> f(m + 1, 0);
for (int i = 1; i <= n; ++i) {
for (int j = A[i - 1]; j <= m; ++j) {
if (f[j - A[i - 1]] + V[i - 1] > f[j]) {
f[j] = f[j - A[i - 1]] + V[i - 1];
}
}
}
return f[m];
}
};