[AlgoExpert] Knapsack Problem

Knapsack Problem

  • Time : O(cap * n)
  • Space : O(cap)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <vector>
using namespace std;

vector<vector<int>> knapsackProblem(vector<vector<int>> items, int cap) {
int ma = 0, pos = 0, n = items.size();
vector<pair<int, int>> dp(cap + 1, {-1, -1});
dp[0] = {0,-1};
for(int j = 0; j < n; j++) {
int c = items[j][0], w = items[j][1];
for(int i = cap; i >= w; i--) {
if(i - w == -1) continue;
if(dp[i].first < dp[i-w].first + c) {
dp[i] = {dp[i-w].first + c, j};
if(ma < dp[i].first) {
ma = dp[i].first;
pos = i;
}
}
}
}
vector<int> res;
while(pos) {
res.push_back(dp[pos].second);
pos -= items[res.back()][1];
}
return {
{ma}, // total value
res, // item indices
};
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/knapsack-problem/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.