Daa Worksheet7 Adityapdf
Daa Worksheet7 Adityapdf
Experiment 7
1. Aim:
Develop a program and analyze complexity to implement 0-1 Knapsack
using Dynamic Programming.
2. Objective
To implement 0-1 Knapsack using Dynamic Programming.
3. Algorithm
o Initialize a 2D table for storing results. o For each item, update the
table with the maximum profit for each weight.
o Consider both including and excluding the item. o Repeat for all
items and capacities.
o The final cell in the table contains the maximum profit.
4. Implemetation/Code
import java.util.Scanner;
public class Class11_1 {
public static int knapsack(int[] weights, int[] values, int capacity, int n) {
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(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i 1][w]);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][capacity];
}
scanner.close();
}
}
5. Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
8. Learning Outcomes:-
• Learn dynamic programming for optimization problems.
• Understand how to solve the knapsack problem efficiently.
• Gain insight into space and time trade-offs.