ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Dynamic Programming: 0/1 Knapsack Problem

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1import java.util.Arrays;
2
3public class Knapsack01 {
4
5/**
6* Solves the 0/1 Knapsack problem using dynamic programming.
7* Given a set of items, each with a weight and a value, determine the maximum value
8* that can be put into a knapsack of a given capacity.
9*
10* @param weights Array of weights of the items.
11* @param values Array of values of the items.
12* @param capacity The maximum weight the knapsack can hold.
13* @return The maximum value that can be obtained.
14*/
15public int solveKnapsack(int[] weights, int[] values, int capacity) {
16if (weights == null || values == null || weights.length != values.length || capacity < 0) {
17throw new IllegalArgumentException("Invalid input parameters.");
18}
19
20int n = weights.length;
21// dp[i][w] will store the maximum value that can be obtained with the first 'i' items
22// and a knapsack of capacity 'w'.
23int[][] dp = new int[n + 1][capacity + 1];
24
25// Base cases:
26// dp[0][w] = 0 for all w: If there are no items, the value is 0.
27// dp[i][0] = 0 for all i: If the capacity is 0, the value is 0.
28// These are implicitly handled by Java's default initialization of int arrays to 0.
29
30// Fill the DP table
31for (int i = 1; i <= n; i++) {
32for (int w = 1; w <= capacity; w++) {
33// If the current item's weight is less than or equal to the current capacity 'w'
34if (weights[i - 1] <= w) {
35// Option 1: Include the current item.
36// Value = value of current item + max value from remaining capacity (w - weights[i-1]) with previous items (i-1).
37int valueIncludingCurrent = values[i - 1] + dp[i - 1][w - weights[i - 1]];
38
39// Option 2: Exclude the current item.
40// Value = max value with previous items (i-1) and the same capacity 'w'.
41int valueExcludingCurrent = dp[i - 1][w];
42
43// Take the maximum of the two options.
44dp[i][w] = Math.max(valueIncludingCurrent, valueExcludingCurrent);
45} else {
46// If the current item's weight is greater than the current capacity 'w',
47// we cannot include it. So, the value is the same as with previous items.
48dp[i][w] = dp[i - 1][w];
49}
50}
51}
52
53// The maximum value will be in dp[n][capacity]
54return dp[n][capacity];
55}
56
57public static void main(String[] args) {
58Knapsack01 ks = new Knapsack01();
59int[] weights = {10, 20, 30};
60int[] values = {60, 100, 120};
61int capacity = 50;
62int maxValue = ks.solveKnapsack(weights, values, capacity);
63System.out.println("Maximum value in Knapsack = " + maxValue); // Expected: 220
64
65int[] weights2 = {1, 3, 4, 5};
66int[] values2 = {1, 4, 5, 7};
67int capacity2 = 7;
68int maxValue2 = ks.solveKnapsack(weights2, values2, capacity2);
69System.out.println("Maximum value in Knapsack = " + maxValue2); // Expected: 9 (items 3 and 4)
70}
71}
Algorithm description viewbox

Dynamic Programming: 0/1 Knapsack Problem

Algorithm description:

This Java code solves the 0/1 Knapsack problem using dynamic programming. The problem is to select items with given weights and values to maximize the total value within a fixed knapsack capacity, where each item can either be taken entirely or not at all. The DP approach builds a table to store optimal solutions for subproblems, leading to an efficient solution for larger instances. This is a classic optimization problem with applications in resource allocation and logistics.

Algorithm explanation:

The `solveKnapsack` method uses a 2D DP table `dp[i][w]`, where `dp[i][w]` represents the maximum value that can be achieved using the first `i` items with a knapsack capacity of `w`. The table is filled iteratively. For each item `i` and capacity `w`, we have two choices: either include the item (if its weight `weights[i-1]` is less than or equal to `w`) or exclude it. If included, the value is `values[i-1] + dp[i-1][w - weights[i-1]]`. If excluded, the value is `dp[i-1][w]`. We take the maximum of these two options. The base cases `dp[0][w] = 0` and `dp[i][0] = 0` are handled by default initialization. The time complexity is O(n * capacity), where `n` is the number of items and `capacity` is the knapsack's capacity. The space complexity is also O(n * capacity) for the DP table.

Pseudocode:

function solveKnapsack(weights, values, capacity):
  n = number of items
  dp = 2D array of size (n+1) x (capacity+1), initialized to 0

  for i from 1 to n:
    for w from 1 to capacity:
      // If current item's weight is less than or equal to current capacity
      if weights[i-1] <= w:
        // Option 1: Include item i
        value_include = values[i-1] + dp[i-1][w - weights[i-1]]
        // Option 2: Exclude item i
        value_exclude = dp[i-1][w]
        dp[i][w] = max(value_include, value_exclude)
      else:
        // Cannot include item i, value is same as without it
        dp[i][w] = dp[i-1][w]

  return dp[n][capacity]