Alghorith Lab 4
Alghorith Lab 4
Lab Report 04
Student Details
Name ID
1.Experiment name :
• 0 - 1 knapsack problem
2. Objective :
This Java code aims to solve the 0-1 Knapsack Problem using dynamic programming. Given a set of
items with associated values and weights, and a maximum weight capacity for a knapsack, the objective
is to determine the maximum value of items that can be placed into the knapsack without exceeding its
capacity. Additionally, the code identifies which specific items are selected for inclusion in the knapsack
to achieve the maximum value..
• 0-1 Knapsack :
The code sets up a dynamic programming table to store optimal solutions, iterates through each item
and weight combination to compute the maximum value achievable, and backtracks to determine the
selected items. Finally, it returns the maximum value and prints the selected items along with their
values and weights, solving the 0-1 Knapsack Problem.
3. Implementation :
class Knapsack {
public static int knapSack(int W, int wt[], int val[], int n,
ArrayList<Integer> selectedItems) { int[][] dp = new
int[n+1][W+1];
int w = W;
for (int i = n; i > 0 && dp[i][w] > 0; i--)
{ if (dp[i][w] != dp[i-1][w])
{ selectedItems.add(i-1);
w -= wt[i-1];
}
}
return dp[n][W];
}
}
public class Main {
OUTPUT:
DISCUSSION
This Java implementation effectively solves the 0-1 knapsack problem using dynamic
programming. It iterates through all items and weights together to calculate the maximum price,
effectively handling restrictions like item weight and baggage allowance. It is also possible to
determine the product options that provide the highest profit by backtracking. The code provides
flexible and scalable solutions to knapsack problems, suitable for many optimization tasks.