MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / knapsack

Function knapsack

cpp/Dynamic Programming/knapsack.cpp:4–26  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2#include <algorithm>
3
4int knapsack(int cap, std::vector<int>& weights, std::vector<int>& values) {
5 int n = values.size();
6 // Base case: Set the first column and last row to 0 by
7 // initializing the entire DP table to 0.
8 std::vector<std::vector<int>> dp(n + 1, std::vector<int>(cap + 1, 0));
9 // Populate the DP table.
10 for (int i = n - 1; i >= 0; i--) {
11 for (int c = 1; c <= cap; c++) {
12 // If the item 'i' fits in the current knapsack capacity,
13 // the maximum value at 'dp[i][c]' is the largest of either:
14 // 1. The maximum value if we include item 'i'.
15 // 2. The maximum value if we exclude item 'i'.
16 if (weights[i] <= c) {
17 dp[i][c] = std::max(values[i] + dp[i + 1][c - weights[i]], dp[i + 1][c]);
18 }
19 // If it doesn't fit, we have to exclude it.
20 else {
21 dp[i][c] = dp[i + 1][c];
22 }
23 }
24 }
25 return dp[0][cap];
26}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected