![]() |
In this article, we will learn about the space-optimized DP solution for the 0-1 Knapsack Problem in Java. Problem StatementA 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.
Example of 0-1 Knapsack ProblemInput: W = 8, n = 3 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 ProblemWe 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,
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
Output
Maximum value of items that the thief can steal is 90 Complexity of the above program:
|
Reffered: https://www.geeksforgeeks.org
Dynamic Programming |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |