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 in small pieces and the total size of items you choose should smaller or equal to M.
ExampleGiven 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 classSolution {2 /**3 * @paramM:an integer m denotes the size of a backpack4 * @paramA & V:given n items with size a[i] and value v[i]5 * @return: The maximum value6 */7 Public intBackpackii (intMint[] A,intv[]) {8 intLen =a.length;9 if(len==0)return-1;Ten One int[] Maxval =New int[Len+1] [M+1]; A for(inti=0;i<=m;i++) -Maxval[0][i]=0; - the for(inti = 1; i<=len;i++) - for(ints=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]; - } + A intMax = 0; at for(inti=0;i<=m;i++) - if(maxval[len][i]>max) max =Maxval[len][i]; - - returnMax; - - in } -}
Lintcode-backpack II