DAA Practical4
DAA Practical4
4. Write a program to solve a 0-1 Knapsack problem using dynamic programming or branch
and bound strategy.Code:
public static int knapSack(int capacity, int[] weights, int[] values, int n) {
if (weights[i - 1] <= w) {
} else {
1. Initialization:
o A 2D array dp is created, where dp[i][w] represents the maximum value achievable with
the first i items and maximum weight w.
o The table is filled iteratively. For each item, we check if it can be included in the knapsack
(if its weight is less than or equal to w):
▪ If it can be included, we take the maximum of either including it (adding its value
and the best we can do with the remaining weight) or not including it.
▪ If it cannot be included, we simply carry forward the maximum value from the
previous item.
3. Result:
Code:
import java.util.Arrays;
import java.util.Comparator;
class Item {
int value;
int weight;
this.value = value;
this.weight = weight;
class Node {
this.level = level;
this.profit = profit;
this.weight = weight;
this.bound = bound;
public static int bound(Node node, int n, int capacity, Item[] items) {
j++;
// If there are still items left, add a fraction of the next item
if (j < n) {
// Function to solve the 0-1 Knapsack problem using Branch and Bound
@Override
});
Node v;
while (!pq.isEmpty()) {
if (u.level == n - 1) {
continue;
}
// Calculate the bound for the new node
Item[] items = {
};
1. Item Class:
o Similar to the previous implementation, we create an Item class to hold the value and
weight of each item.
2. Node Class:
o The Node class represents a node in the decision tree, containing information about the
level, profit, weight, and upper bound.
3. Bound Calculation:
o The bound method calculates the upper bound of profit for a given node, taking into
account the current profit and the potential profit from the remaining items.
o The knapsack function begins by sorting the items based on their value-to-weight ratio
in descending order.
o It iteratively explores nodes, adding either the next item or skipping it, while updating
the maximum profit found.
5. Main Method:
o The main method initializes the items and capacity, then calls the knapsack function to
calculate and print the maximum profit.