Algorithm Design and Analysis (ADA) : Dynamic Programming I
Algorithm Design and Analysis (ADA) : Dynamic Programming I
(ADA)
CSE222
Dynamic Programming I
29 1 21
The First Example
2 5 6 4 3 5
x v x
x r
Mon Un Un
2 5 6 4 3 5
2 5 6 4 3 5
use 4 recursions
i 4 T M2 C
Tcn
OCny
Understanding the Optimal Solution
t
2 5 6 4 5 3
Observation : Last ball is not part of the optimal
solution
Understanding the Optimal Solution
x
y
2 5 6 4 5 3
Last ball is not part of the optimal solution
x w
2 4 6 4 3 5
Last ball is part of the optimal solution
So, second last ball cannot be !
Understanding the Optimal Solution
r
2 4 6 4
I 3 5
Last ball is part of the optimal solution
Hence, second last ball cannot be !
Remaining green balls form an optimal solution to
the remaining instance (Why?) Proof by contradiction
Towards an Algorithm
Return max{𝑤1 , 𝑤2 }
A Recursive Algorithm : Runtime
Tcn Runtime for
SelectBalls (𝑏1 , 𝑏2 , ⋯ 𝑏𝑛 ) by.bz bn
If n=1, return 𝑏1 Else
T n 1 n e t Tcn 2 Cc
𝑤1 = SelectBalls(𝑏1 , 𝑏2 , ⋯ 𝑏𝑛−1 )
𝑤2 = SelectBalls(𝑏1 , 𝑏2 , ⋯ 𝑏𝑛−2 ) + weight
of 𝑏𝑛
TG p
I
Return max{𝑤1 , 𝑤2 } Golden Ratio
Why is the Runtime So Horrible ?
Soleil
l
Sola y Solar 2
skcn
Gg
sfsncn.gg
The MOST important insight
Memoization
Eliminating Redundancy
Tab.LI 0ptsoen
Tab : Array of size 𝑛
by.bz obi
SelectBalls (𝑏1 , 𝑏2 , ⋯ 𝑏𝑛 ) of
If Tab[n] is valid return Tab[n] else
𝑤1 = SelectBalls(𝑏1 , 𝑏2 , ⋯ 𝑏𝑛−1 )
𝑤2 = SelectBalls(𝑏1 , 𝑏2 , ⋯ 𝑏𝑛−2 ) + weight
L
Tab[n] = max{𝑤1 , 𝑤2 }
of 𝑏𝑛
Eliminating Redundancy : Even Better Solution
Tab : Array of size 𝑛
SelectBalls (𝑏1 , 𝑏2 , ⋯ 𝑏𝑛 )
0 Tab Il max 0 weight bis
Tab o
i 2 to n
for Tab i i
Tab it mae
Tab i 2 t weight bi
of
Recovery the Solution
Noextraspi g
o o o O
o