[InterviewBit] 0-1 Knapsack

0-1 Knapsack

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
int Solution::solve(vector<int> &A, vector<int> &B, int C) {
vector<int> dp(C + 1, INT_MIN);
dp[0] = 0;
for(int i = 0; i < A.size(); i++) {
int a = A[i], b = B[i];
for(int j = C; j >= b; j--) {
dp[j] = max(dp[j], dp[j-b] + a);
}
}

return *max_element(begin(dp),end(dp));
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/31/PS/interviewbit/0-1-knapsack/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.