Dynamic programming is a technique used in computer programming to solve problems with overlapping subproblems and optimal substructure properties. The 0/1 knapsack problem aims to maximize profit while keeping the total weight of items within a knapsack's capacity. The algorithm has a time complexity of O(n*w) and uses a 2-D array for storage.
DESIGN TECHNIQUE
Example /Problem
Algorithm Design
Technique
Dynamic Programing
0/1 Dynamic Programming
Knapsack Problem
3.
Dynamic Programming
Technique
DynamicProgramming is a technique in computer programming
that helps to efficiently solve a class of problems that have
overlapping subproblems and optimal substructure property.
If any problem can be divided into subproblems, which in turn
are divided into smaller subproblems, and if there are overlapping
among these subproblems, then the solutions to these
subproblems can be saved for future reference. In this way,
efficiency of the CPU can be enhanced. This method of solving a
solution is referred to as dynamic programming.
4.
0/1 DP KNAPSACKPROBLEM
• Knapsack is basically means bag. A bag of given capacity. We want to pack n
items in your luggage.
• Input:
Knapsack of capacity
List (Array) of weight and their corresponding value.
• Output: To maximize profit and minimize weight in capacity.
The knapsack problem where we have to pack the knapsack with
maximum value in such a manner that the total weight of the items should not
be greater than the capacity of the knapsack.
5.
0/1 DP KNAPSACKPROBLEM
Weights
• Items –
Profit
Bag = Weight = ? Kg. W
1) 0/1 Problem
0 or 1 Suppose,
2 Kg
1Kg 2kg
DP Method
2) Fractional Problem
Suppose,
3 Kg
2 Kg 1 Kg
Greedy Method
6.
Example of 0/1DP Knapsack
Problem
• Consider the following instance of knapsack problem
N = 4 , Weights = { 3, 4, 6, 5}
W = 8 , Profits (Values) = { 2, 3, 1, 4}
Find out the optimal solution for the given
instance.
Given: Weights = { 3, 4, 6, 5},
Profits (Values) = { 2, 3, 1, 4},
W = 8 ,
N = 4 .
Algorithm of KnapsackProblem
Dynamic-0-1-knapsack (v, w, n, W)
{
for w = 0 to W do
c[0, w] = 0
for i = 1 to n do
c[i, 0] = 0
for w = 1 to W do
if wi ≤ w then
if vi + c[i-1, w-wi] then
c[i, w] = vi + c[i-1, w-wi]
else c[i, w] = c[i-1, w]
else
c[i, w] = c[i-1, w]
}
Time Complexity of0/1 DP Knapsack Problem
Complexity Analysis
Time Complexity: O(N*W).
where ‘N’ is the number of weight element and ‘W’ is capacity.
• As for every weight element we traverse through all weight
capacities 1<=w<=W.
• Auxiliary Space: O(N*W).
The use of 2-D array of size ‘N*W’.