LintCode-BackPack II

LiBlog發表於2015-01-01

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 }

 

相關文章