[Hacker Rank] Knapsack

Knapsack

  • Time : O(kn)
  • Space : O(k)
1
2
3
4
5
6
7
8
9
10
11
int unboundedKnapsack(int k, vector<int> arr) {
bool dp[2001] = {};
dp[0] = true;
for(auto& a : arr) {
for(int i = a; i <= k; i++)
dp[i] |= dp[i-a];
}
for(int i = k; i >= 0; i--)
if(dp[i]) return i;
return -1;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/16/PS/HackerRank/unbounded-knapsack/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.