Problem statement task- Knapsack 0/1
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively.
Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or don’t pick it (0-1 property).
Self- understanding
Java Code Implementation
public class Knapsack01DP {
// Driver program to test above function
public static void main(String args[]) {
int val[] = new int[] {1,4,5,7 };
int wt[] = new int[] {1,3,4,5 };
int W = 7;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
}
// A utility function that returns maximum of two integers
static int max(int a, int b) {
return (a > b) ? a : b;
}
// Returns the maximum value that can be put in a knapsack of capacity W
static int knapSack(int W, int wt[], int val[], int n) {
int i, w;
int temp[][] = new int[n + 1][W + 1];
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i == 0 || w == 0)
temp[i][w] = 0;
else if (wt[i - 1] <= w)
temp[i][w] = max(val[i - 1] + temp[i - 1][w - wt[i - 1]],temp[i - 1][w]);
else // directly taking top value
temp[i][w] = temp[i - 1][w];
}
}
return temp[n][W];
}
}
Time Complexity: O(nW) where n is the number of items and W is the capacity of knapsack.

No comments:
Post a Comment