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

Class Knapsack

java/Dynamic Programming/Knapsack.java:1–26  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected