01 Knapsack
01 Knapsack
PROBLEM
0/1 KNAPSACK PROBLEM
EXPLANATION
⮚ Given N items where each item has some weight and profit
associated with it and also given a bag with capacity W,
[i.e., the bag can hold at most W weight in it].
⮚ The task is to put the items into the bag such that the
sum of profits associated with them is the maximum
possible.
Input:
N = 3
W = 4
values[] = {1,2,3}
weight[] = {4,5,1}
Output: 3
Explanation: Choose the last item that weighs 1 unit
and holds a value of 3
0/1 KNAPSACK PROBLEM
ALGORITHM
GREEDY APPROACH
0/1 KNAPSACK PROBLEM
GREEDY APPROACH
0/1 KNAPSACK PROBLEM
APPLICATION
Sample IO
Input
wt ={10, 40, 20, 30}
val = {60, 40, 100, 120}
capacity = 50
Output
240
Time Complexity
O(n log n)
0/1 KNAPSACK PROBLEM
import java.util.Arrays;
import java.util.Comparator;
public class FractionalKnapSack {
private static double
getMaxValue(int[] wt, int[] val, int
capacity)
{
ItemValue[] iVal = new
ItemValue[wt.length];
for (int i = 0; i < wt.length; i++) {
iVal[i] = new
ItemValue(wt[i], val[i], i);
}
Arrays.sort(iVal, new
Comparator<ItemValue>() {
@Override
0/1 KNAPSACK PROBLEM
public int compare(ItemValue o1, ItemValue
o2)
{
return o2.cost.compareTo(o1.cost);
}
});
double totalValue = 0d;
break;
}
}
return totalValue;
}
System.out.println(maxValue);
}
}
0/1 KNAPSACK PROBLEM
TIME AND SPACE COMPLEXITY