Skip to content

Commit

Permalink
Added knapsack 0/1 function
Browse files Browse the repository at this point in the history
  • Loading branch information
spirosmaggioros committed Nov 18, 2024
1 parent fac919c commit acd0cca
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/algorithms/dynamic_programming/knapsack.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#ifndef KNAPSACK_H
#define KNAPSACK_H

#ifdef __cplusplus
#include <iostream>
#include <vector>
#include <utility>
#endif

/**
* @brief knapsack 0/1 function
* @param v the passed vector
* @param capacity the capacity of the knapsack
* @return int: the maximum value you can collect with a knapsack of the passed capacity
*/
int knapsack(std::vector<std::pair<int, int> > &v, int capacity) {
if(capacity == 0) {
return 0;
}

int n = int(v.size());
std::vector<std::vector<int > > dp(n + 1, std::vector<int>(capacity + 1));

for(int i = 1; i<=n; i++) {
for(int j = 0; j<=capacity; j++) {
dp[i][j] = dp[i - 1][j];
if(i == 0 || j == 0) {
dp[i][j] = 0;
}
else if(v[i - 1].first <= j) {
dp[i][j] = std::max(dp[i - 1][j], v[i - 1].second + dp[i - 1][j - v[i - 1].first]);
}
}
}

return dp[n][capacity];
}

#endif
12 changes: 12 additions & 0 deletions tests/algorithms/dynamic_programming/knapsack.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#include "../../../third_party/catch.hpp"
#include "../../../src/algorithms/dynamic_programming/knapsack.h"

TEST_CASE("Testing knapsack 0/1 [1]") {
std::vector<std::pair<int, int> > v = {{10, 60}, {20, 100}, {30, 120}};

REQUIRE(knapsack(v, 50) == 220);
v.clear();
v = {{5, 40}, {3, 20}, {6, 10}, {3, 30}};

REQUIRE(knapsack(v, 10) == 70);
}

0 comments on commit acd0cca

Please sign in to comment.