How to solve Knapsack problem using Dynamic Programming
💻 coding

How to solve Knapsack problem using Dynamic Programming

2 min read 482 words
2 min read
ShareWhatsAppPost on X
  • 1The knapsack problem involves selecting items with maximum value without exceeding a weight limit, relevant in various fields like computer science and finance.
  • 2Dynamic programming can optimize the knapsack problem solution, reducing the time complexity from exponential to polynomial by storing previously calculated results.
  • 3The provided Java code demonstrates a dynamic programming approach to solve the knapsack problem, efficiently calculating maximum profit within weight constraints.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The knapsack problem involves selecting items with maximum value without exceeding a weight limit, relevant in various fields like computer science and finance."

How to solve Knapsack problem using Dynamic Programming

The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.

The problem often arises in resource allocation where there are financial constraints and is studied in fields such as combinatorics, computer science, complexity theory, cryptography, applied mathematics, and daily fantasy sports.

The knapsack problem has been studied for more than a century, with early works dating as far back as 1897. The name "knapsack problem" dates back to the early works of mathematician Tobias Dantzig (1884–1956) and refers to the commonplace problem of packing the most valuable or useful items without overloading the luggage.

We will solve this problem using recursion :

package dp;

public class Knapsack {

	public static void main(String[] args) {
		int[] values = new int[] {60, 100, 120};
		int[] weight = new int[] {10, 20, 30};
		int maxWeight = 50;
		
		long startTime = System.nanoTime();
		
		System.out.println(MaxProfit(values, weight, maxWeight, values.length-1));

		long endTime = System.nanoTime();
		long totalTime = endTime - startTime;
		System.out.println("Total Time (nanoseconds) : " + (totalTime));
	}

	private static int MaxProfit(int[] values, int[] weight, int maxWeight, int index) {
		if(maxWeight <= 0 || index < 0)
			return 0;
		
		//Either ignore the current item or take the current item.
		return max(MaxProfit(values, weight, maxWeight,index-1), 
				values[index] + MaxProfit(values, weight, maxWeight-weight[index], index-1));
	}

	private static int max(int a, int b) {
		return a>b?a:b;
	}

}
output:

220
Total Time (nanoseconds) : 164625

If you look carefully we are solving the same overlapping problem again and again. The time complexity of the above solution is exponential, i.e 2^n.

Can we improve the above solution?

Yes by using Dynamic Programming and remembering the previously calculated results.

package dp;

public class Knapsack {

	public static void main(String[] args) {
		int[] values = new int[] {60, 100, 120};
		int[] weight = new int[] {10, 20, 30};
		int maxWeight = 50;
		
		long startTime = System.nanoTime();
		
		System.out.println(MaxProfit(values, weight, maxWeight));

		long endTime = System.nanoTime();
		long totalTime = endTime - startTime;
		System.out.println("Total Time (nanoseconds) : " + (totalTime));
	}

	private static int MaxProfit(int[] values, int[] weight, int maxWeight) {
		if(maxWeight <= 0)
			return 0;
		
		int[][] dp = new int[values.length+1][maxWeight+1];
		
		for(int i=0;i<values.length;i++) {
			for(int j=0;j<=maxWeight;j++) {
				if(i==0 || j==0)
					dp[i][j]=0;
				else if(weight[i]<=j) {
					dp[i][j]=max(values[i]+dp[i-1][j-weight[i]],dp[i-1][j]);
				}
				else {
					dp[i][j] = dp[i-1][j];
				}
			}
		}
		return dp[values.length-1][maxWeight];
	}

	private static int max(int a, int b) {
		return a>b?a:b;
	}

}
output:

220
Total Time (nanoseconds) : 239009

The time complexity of the above solution is O(nW) where n is the number of items and W is the capacity of Knapsack.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 31 July 2018 · 2 min read · 482 words

Part of AskGif Blog · coding

You might also like

How to solve Knapsack problem using Dynamic Programming | AskGif Blog