Description
Given n kind of items with size Ai and 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.
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 15
Solution
此题允许重复放置,因此第二层循环是从小到大正向遍历
因为只有A[i]<=j时才更新dp[j],因此j循环做一个小小的优化直接从A[i]开始遍历
public class Solution {
/**
* @param m: An integer m denotes the size of a backpack
* @param A: Given n items with size A[i]
* @return: The maximum size
*/
public int backPackIII(int[] A, int[] V, int m) {
int[] dp = new int[m+1];
for (int i = 0; i < A.length; i++) {
for (int j = A[i]; j <= m; j++) {
dp[j] = Math.max(dp[j], dp[j-A[i] + V[i]]);
}
}
return dp[m];
}
}