码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode-BackPack II

时间:2015-01-01 01:24:21      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4196877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!