Lintcode-backpack II

Source: Internet
Author: User
Tags lintcode

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.