Course Name: DAA Lab Course Code: 21ITH-311/21CSH-311
Experiment 2.3
Aim: Develop a program and analyze complexity to implement 0-1 Knapsack using dynamic
programming.
Objectives: to implement 0-1 Knapsack using Dynamic Programming
Input/Apparatus Used: Online GDB compiler.
Algorithm:
1. The method knapsack takes three arguments: an array of values, an array of weights, and the capacity
of the knapsack. It returns the maximum value that can be obtained.
2. n represents the number of items, which is determined by the length of the values array.
3. An array dp is created to store the maximum value that can be obtained at each capacity for different
numbers of items.
4. The nested loops iterate through each item and each possible capacity, considering all subproblems from
0 to the current number of items and capacity.
5. The base case is handled first. When there are no items (i = 0) or the knapsack capacity is 0 (w = 0), the
maximum value that can be obtained is 0.
6. If the current item's weight is less than or equal to the current capacity, the maximum value is either the
maximum of the value excluding the current item or the value including the current item and the
maximum value obtained from the remaining capacity.
7. If the current item's weight is greater than the current capacity, the maximum value is the same as the
maximum value obtained without considering the current item.
Name: Harsh Gupta UID: 21BCS10721
Course Name: DAA Lab Course Code: 21ITH-311/21CSH-311
Sample Code:
public class knapsack {
public static int knapsack(int[] values, int[] weights, int capacity) {
int n = values.length;
int[][] dp = new int[n + 1][capacity + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= capacity; w++) {
if (i == 0 || w == 0) {
dp[i][w] = 0;
} else if (weights[i - 1] <= w) {
dp[i][w] = Math.max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][capacity];
}
public static void main(String[] args) {
int[] values = {60, 100, 120};
int[] weights = {10, 20, 30};
int capacity = 50;
int maxValue = knapsack(values, weights, capacity);
System.out.println("Maximum value that can be obtained: " + maxValue);
}
}
Output:
Time Complexity:
O(n*capacity)
Name: Harsh Gupta UID: 21BCS10721