Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions c++/0-1 knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <bits/stdc++.h>
using namespace std;


int weight[] = {10, 20, 30};
int value[] = {60, 100, 120};
int dp[1000][1000];

int knapsack(int weight_left, int index) {
if (index == -1 or weight_left < weight[index]) return 0;
if (~dp[weight_left][index]) return dp[weight_left][index];
int a = knapsack(weight_left, index-1);
int b = knapsack(weight_left - weight[index], index-1) + value[index];
return dp[weight_left][index] = max(a, b);
}

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
memset(dp, -1, sizeof dp);
int bag_weight = 50;
int items = 3;
cout << knapsack(bag_weight, items);
}