LintCode-BackPack II
2015-01-01 00:07
267 查看
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:
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:
public class Solution { /** * @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 */ public int backPackII(int m, int[] A, int V[]) { int len = A.length; if (len==0) return -1; int[][] maxVal = new int[len+1][m+1]; for (int i=0;i<=m;i++) maxVal[0][i]=0; for (int i = 1; i<=len;i++) for (int s=0; s<=m; s++){ maxVal[i][s] = maxVal[i-1][s]; if (s>=A[i-1] && maxVal[i][s]<maxVal[i-1][s-A[i-1]]+V[i-1]) maxVal[i][s] = maxVal[i-1][s-A[i-1]]+V[i-1]; } int max = 0; for (int i=0;i<=m;i++) if (maxVal[len][i]>max) max = maxVal[len][i]; return max; } }
相关文章推荐
- 【LintCode】 Backpack II 背包问题II
- LintCode - Backpack II
- lintcode-medium-Backpack II
- LintCode-38.搜索二维矩阵 II
- Lintcode - k sum II
- lintcode 547两数组的交 lintcode 548两数组的交II
- 翻转链表 II-LintCode
- LintCode:最大子数组 II
- lintcode-63-搜索旋转排序数组 II
- lintcode-83-落单的数 II
- 删除排序链表中的重复数字 II -LintCode
- [LintCode]113.删除排序链表中的重复数字 II
- python - LintCode 4. 丑数 II
- LintCode:46. 主元素I VS 47. 主元素 II VS 48. 主元素 III
- LintCode: Single Number II
- LintCode 二叉树的层次遍历 II
- [Lintcode]Remove Duplicates from Sorted List II 删除排序链表中的重复数字 II
- *[Lintcode]Merge Sorted Array II
- lintcode-easy-Merge Sorted Array II
- lintcode:买卖股票的最佳时机 II