首页 > 代码库 > LintCode-BackPack II
LintCode-BackPack II
Given n items with size A[i] and value V[i], and a backpack with size m. What‘s the maximum value can you put into the backpack?
Note
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.
Solution:
1 public class Solution { 2 /** 3 * @param m: An integer m denotes the size of a backpack 4 * @param A & V: Given n items with size A[i] and value V[i] 5 * @return: The maximum value 6 */ 7 public int backPackII(int m, int[] A, int V[]) { 8 int len = A.length; 9 if (len==0) return -1;10 11 int[][] maxVal = new int[len+1][m+1];12 for (int i=0;i<=m;i++)13 maxVal[0][i]=0;14 15 for (int i = 1; i<=len;i++)16 for (int s=0; s<=m; s++){17 maxVal[i][s] = maxVal[i-1][s];18 if (s>=A[i-1] && maxVal[i][s]<maxVal[i-1][s-A[i-1]]+V[i-1])19 maxVal[i][s] = maxVal[i-1][s-A[i-1]]+V[i-1];20 }21 22 int max = 0;23 for (int i=0;i<=m;i++)24 if (maxVal[len][i]>max) max = maxVal[len][i];25 26 return max;27 28 29 }30 }
LintCode-BackPack II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。