Open In App

Space Optimized DP Solution for 0-1 Knapsack Problem in Java

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about the space-optimized DP solution for the 0-1 Knapsack Problem in Java.

Problem Statement

A thief wants to rob a store at someplace. The thief is carrying a bag ( i.e. Knapsack ) of capacity W and the store has n number of total items, their weights, and values are given in two different arrays wt[0… N-1] and val[0… N-1]. He is allowed to either carry ( include ) or not carry ( exclude ) an item i.e. 0 or 1. Find the maximum value that the thief can steal from N items of the store.

Note: The thief cannot choose the fraction of items. He can either take it or can not take it.

Example of 0-1 Knapsack Problem

Input: W = 8, n = 3
val[] = {30, 50, 60}
wt[] = {3, 4, 5}

Output: 90

Explanation: We can choose items with weight 3KG and 5KG, and will get maximum value as 90

To know more about the whole topic refer to What is 0-1 Knapsack problem and its types.

Java Program for Space Optimized DP solution for 0-1 Knapsack Problem

We have already discussed a Dynamic Programming (DP) Solution here. In this approach, we are going to reduce the extra space that we have used in the tabulation approach. So, The main idea behind this space optimization is, that if we carefully look at the relationship,

dp[i][cap] = max(dp[i-1][cap] ,dp[i-1][cap-wt[i]]

then we observe that to calculate the value of a current cell of the array we only need the previous row values i.e. prev, So, we can use only one row, there is no need to store the entire array Hence we can space optimize it.

Below is the implementation of the Space Optimized DP solution for 0-1 Knapsack Problem:

Java




import java.util.*;
  
class maxKnapsack {
    // Function to solve the 0/1 Knapsack problem through DP
    static int knapsack(int[] wt, int[] val, int n, int W) {
        // create an array to store the previous row i.e. maximum value for each capacity
        int prev[] = new int[W + 1];
  
        // Initialize prev array's first row
        for (int i = wt[0]; i <= W; i++) {
            prev[i] = val[0];
        }
  
        // Iterate through each item and capacity
        for (int i = 1; i < n; i++) {
            for (int cap = W; cap >= 0; cap--) {
                //Do Not Take current item = Calculate maximum value
                int notTaken = prev[cap];
  
                //Take current item = Calculate maximum value
                int taken = Integer.MIN_VALUE;
                if (wt[i] <= cap) {
                    taken = val[i] + prev[cap - wt[i]];
                }
  
                // Update the prev array with the maximum value for the current capacity
                prev[cap] = Math.max(notTaken, taken);
            }
        }
  
        //Output is stored in the last element of the previous array
        return prev[W];
    }
  
    public static void main(String args[]) {
        int wt[] = {3,4,5};
        int val[] = {30,50,60};
        int W = 8;
        int n = wt.length;
  
        // Calculate and print the maximum amount of items the thief can steal
        System.out.println("Maximum value of items that the thief can steal is " + knapsack(wt, val, n, W));
    }
}


Output

Maximum value of items that the thief can steal is 90


Complexity of the above program:

Time complexity: O(n * W)
Auxiliary space: O(W)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads