Skip to content

Commit

Permalink
0-1 knapsack using dynamic programming
Browse files Browse the repository at this point in the history
  • Loading branch information
salonigupta63 authored Oct 20, 2018
1 parent b386391 commit 2fc6c7a
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions 1-0_knapsack_problem/0-1_knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//0-1 Knapsack problem using dynamic programming
#include<iostream.h>

int max(int a, int b) { return (a > b)? a : b; }

int knapSack(int W, int wt[], int val[], 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(val[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];
}

void main()
{
int val[] = {50, 110, 115};
int wt[] = {10, 20, 30};
int W = 50;
int n = 1;
int c=knapSack(W, wt, val, n);
cout<<c;
}

0 comments on commit 2fc6c7a

Please sign in to comment.