Saving Memory In Dynamic Programming

Revision en1, by Karan2116, 2015-08-15 19:40:16

I am trying to practice some problems in dynamic programming. Now there are memory constraints and i want to manage the memory efficiently for which i want to maintain only those rows on which the final answer depends.

For instance in knapsack,I want to maintain only two rows. I am trying it in the following way but failing.

long long int knapSack(long long W, vector<long long> &wt, vector<long long> &val, int n)
{
   long long int i, w;
   long long int K[2][W+1];
   for (i = 0; i <= n; i++)
   {
       for (w = 0; w <= W; w++)
       {
           if (i==0 || w==0)
               K[i%2][w] = 0;
           else if (wt[i-1] <= w)
                 K[i%2][w] = max(val[i-1] + K[(i-1)%2][w-wt[i-1]],  K[(i-1)%2][w]);
           else
                 K[i%2][w] = K[(i-1)%2][w];
       }
   }
   return K[n%2][W];
}

Haven't tried it before and could not find some useful material. It would be great if someone can guide.

Tags dp, memory manipulation

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English Karan2116 2015-08-15 19:40:16 1011 Initial revision (published)