Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save KhaledElshamy/d0b952d5377db8c06a6bf49e5c67965e to your computer and use it in GitHub Desktop.

Select an option

Save KhaledElshamy/d0b952d5377db8c06a6bf49e5c67965e to your computer and use it in GitHub Desktop.
Take as much gold as possible (Dynamic programming) algorithmic toolbox course at coursera
#include <bits/stdc++.h>
using namespace std;
int max(int a, int b) { return (a > b)? a : b; }
int knapSack(int W, int wt[], int n)
{
int i, w;
int K[n+1][W+1];
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(wt[i-1]+ K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
int main()
{
int W,numbers;
cin>>W>>numbers;
int wt[numbers] ;
for(int i=0;i<numbers;i++)
cin>>wt[i];
cout<<knapSack(W, wt, numbers)<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment