Dynamic Programming 6
Dynamic Programming 6
November 2022
CSE201
Dynamic Programming
Characteristics
Dynamic programming is applicable when the problem satisfies the
following properties.
1 Optimal substructure: The problem can be broken into
sub-problems and the optimal solutions of the subproblems can be
combined to obtain the optimal solution to the main problem.
2 Overlapping sub-problem: The solutions to the smaller subproblems
can be reused repeatedly to obtain the solutions to the larger
sub-problems rather than always generating new subproblems.
Fn = Fn−1 + Fn−2
Fibo(n)
Begin
if n ≤ 1 then
Return n;
else
Return Fibo(n-1) + Fibo(n-2);
endif
End
Definition
Given the dimension of a sequence of matrices, the task is to find the
most efficient way to multiply these matrices together such that the
total number of element multiplications is minimum.
Example
Input: arr[] = {40, 20, 30, 10, 30}
There are 4 matrices of dimensions A40×20 , B20×30 , C30×10 , D10×30 .
The minimum number of multiplications is obtained by putting
parenthesis in the following way: (A(BC))D
The minimum is 20*30*10 + 40*20*10 + 40*10*30 = 26000
Solution idea
1 Initialization: Find the number of multiplications required to
multiply two adjacent matrices.
2 Iteration: Use these values to find the minimum multiplication
required for matrices in a range of length 3 and further use those
values for ranges with higher lengths.
3 Termination: Build on the answer in this manner till the range
becomes [0, N-1].
m14x10
m210x3
m33x12
m412x20
m520x7
(November 2022) Dynamic Programming CSE201 13 / 18
Example
m (1,2) = m1 x m2 = 4 x 10 x 3 = 120
m (2, 3) = m2 x m3 = 10 x 3 x 12 = 360
m (3, 4) = m3 x m4 = 3 x 12 x 20 = 720
m (4,5) = m4 x m5 = = 12 x 20 x 7 = 1680
m[1,3] = m1 m2 m3
m[2,4] = m2 m3 m4
m[3,5] = m3 m4 m5
m[1,4] = m1 m2 m3 m4
m[2,5] = m2 m3 m4 m5
m[1,5] = m1 m2 m3 m4 m5