Friday, January 24, 2014

Knapsack problem with 1 parameter

The probelm statement
We have a bag which can carry upto M kilograms of weight. We have N different items each with its own weight. We need to get out bag as full as possible. What is the maximum wieght we can carry?
 Sample
    5 20
   4 10 7 1 8
Here M is 20 and there are 5 elements to choose from . Here is the algorithm, we keep a  boolean array . The element I will show If we can collect the weight I . 
Initially all are marked as false. 
 for i=1 to N
mark[a[i]]=true;
because we can collect a weight equal to every element of the main array.
Then we need to loop over our mark array from back (If we can use one item multiple times then we need to loop from the beginning) and when we came to an element which has a value of true (suppose the index of that element is I) we need to loop over our given array and turn mark[I+a[j]] into true => If we can collect the value I we can also collect teh value I plus one more given element.Then we just need to find the biggest element which has a vlue of true in the mark array and is closest to M.  

No comments:

Post a Comment