Dynamic Programming¶
What if the sub-problems overlap?
- Sub-problems share sub-sub-problems.
A DaC algorithm would do more work than necessary, because it needs to repeatedly solve the overlapped sub-sub-problems.
A Dynamic Programming algorithm solves each sub-sub-problem only once and then saves its result (in array or hash table), thus avoiding the work of repeatedly solving the common sub-sub-problems.
Example - Fibonacci Numbers¶
A rabbit was born in the beginning.
A rabbit starts producing offspring on the second generation after its birth and produces one child each generation.
How many rabbits will there be after n generations?
Straightforward Recursive¶
F(0)=0,\space F(1)=1
0,1,1,2,3,5,8,13,21,34,...
1 2 3 |
|
This is slow!
Here's why:
The same value is calculated over and over!
- Sub-problems are overlapping – they share sub-sub-problems.
Solution¶
Dynamic Programming!
We can calculate F(n) in linear time, by remembering solutions to the solved sub-problems.
Compute solution in a bottom-up fashion.
1 2 3 4 5 6 |
|
Optimization Problems¶
DP is typically applied to optimization problems.
Optimization problems can have many possible solutions, each solution has a value, and we wish to find a solution with the optimal value (e.i. minimum or maximum).
An algorithm should compute the optimal value plus, if needed an optimal solution.
Example - Rod Cutting¶
Problem:
- A steel rod of length n should be cut and sold in pieces.
- Pieces sold only in integer sizes according to a price table P[1..n]
Goal:
- Cut up the rod to maximize profit.
r_n: the maximum profit of cutton a rod with length n. $$ r_n=max(P[1]+r_{n-1},P[2]+r_{n-2},...,P[n-1]+r_1,P[n]+r_0) $$
-
Having a rod with length 1, i.e., P[1], and the maximum profit of the remaining rod with length n-1, i.e., r_{n-2}
-
Having a rod with length 2, i.e., P[2], and the maximum profit of the remaining rod with length n - 2, i.e., r_{n-2}
- …
- Having a rod with length n, i.e., P[n], and the maximum profit of the remaining rod with length 0, i.e., r_=0
We say that the rod cutting problem exhibits optimal substructure.
1 2 3 4 5 6 |
|
Running time is Exponential!
See analysis on lecture 9 slides, slide 28-30
Memoization - Top-Down¶
Remember the solutions in an array or a hash-table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Running Example¶
See on lecture 9 slides, slide 35-46
Run time is Quadratic.