Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Created May 16, 2019 16:58
Show Gist options
  • Save manojnaidu619/cabf97fa6176a2eb7f5baaf55aae3c89 to your computer and use it in GitHub Desktop.
Save manojnaidu619/cabf97fa6176a2eb7f5baaf55aae3c89 to your computer and use it in GitHub Desktop.
0/1 Knapsack to find maximized benefit using Dynamic programming in C
#include <stdio.h>
#include <stdlib.h>
int max(int a,int b){
return (a>b) ? a : b;
}
void knapsack(int n, int W, int val[], int wt[]){
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];
}
}
}
printf("Max profit : %d\n", K[n][W]);
}
int main(){
int n,W,wt[50],val[50];
printf("Enter the no of objects : ");
scanf("%d",&n);
printf("Enter weights and values respectively : \n");
for(int i=0;i<n;i++){
scanf("%d%d",&wt[i],&val[i]);
}
printf("Enter the capacity : ");
scanf("%d",&W);
knapsack(n,W,val,wt);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment