5.1 Dynamic Programming
5.1 Dynamic Programming
UNIVERSITY INSTITUTE OF
ENGINEERING
COMPUTER SCIENCE
ENGINEERING
Bachelor of Engineering
Design and Analysis of
Algorithms(CSH-311/ITH-311)
Outcome:
• Student will understand
Concept of dynamic programming
Applications of DP
Dynamic Programming
0-1 Knapsack
Problem Statement:
A thief is robbing a store and can carry a maximal weight
of W into his knapsack. There are n items and weight
of ith item is wi and the profit of selecting this item is pi.
What items should the thief take?
Dynamic-Programming Approach
• Let i be the highest-numbered item in an optimal
solution S for W dollars. Then S' = S - {i} is an optimal
solution for W - wi dollars and the value to the
solution S is Vi plus the value of the sub-problem.
• We can express this fact in the following formula:
define c[i, w] to be the solution for items 1,2, … , i and the
maximum weight w.
• The algorithm takes the following inputs
• The maximum weight W
• The number of items n
• The two sequences v = <v1, v2, …, vn> and w = <w1, w2, …,
wn>
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
Dynamic-0-1-knapsack (v, w, n, W)
Example:
int[ ] A = { 3, 2, 7, 1}, S = 6
Output: True, subset is (3, 2, 1}
Recursive Approach
• For every element in the array has two options, either we
will include that element in subset or we don’t include it.
• So if we take example as int[] A = { 3, 2, 7, 1}, S = 6
• If we consider another int array with the same size as A.
• If we include the element in subset we will put 1 in that
particular index else put 0.
• So we need to make every possible subsets and check if
any of the subset makes the sum as S.
• If we think carefully this problem is quite similar to
“Generate All Strings of n bits”
Time Complexity: O(2n).
REFERENCES
Text books:
•Cormen, Leiserson, Rivest, Stein, “Introduction to Algorithms”, Prentice Hall of
India, 3rd edition 2012. problem, Graph coloring.
•Horowitz, Sahni and Rajasekaran, “Fundamentals of ComputerAlgorithms”,
University Press (India), 2nd edition
Websites:
• https://www.tutorialspoint.com/design_and_analysis_of_algorithms/
design_and_analysis_of_algorithms_01_knapsack.htm
• https://algorithms.tutorialhorizon.com/dynamic-programming-subset-sum-
problem/
• https://www.codesdope.com/course/algorithms-coin-change/
Summary
Dynamic programming:
•The general method
•0/1 knapsack
•Subset Sum problem
•Change making problem