2.3 Daa
2.3 Daa
Experiment 2.3
Aim: Develop a program and analyze complexity to implement 0-1 Knapsack using dynamic
programming.
Algorithm:
1. The method knapsack takes three arguments: an array of values, an array of weights, and the capacity
2. n represents the number of items, which is determined by the length of the values array.
3. An array dp is created to store the maximum value that can be obtained at each capacity for different
numbers of items.
4. The nested loops iterate through each item and each possible capacity, considering all subproblems from
5. The base case is handled first. When there are no items (i = 0) or the knapsack capacity is 0 (w = 0), the
6. If the current item's weight is less than or equal to the current capacity, the maximum value is either the
maximum of the value excluding the current item or the value including the current item and the
7. If the current item's weight is greater than the current capacity, the maximum value is the same as the
return dp[n][capacity];
}
Time Complexity:
O(n*capacity)