Professional Documents
Culture Documents
1 / 24
Dynamic Programming – A Simple Example
2 / 24
Fibonacci Numbers (continued)
Remedy:
Avoid recomputation of values by saving them in a table and
use them when they are needed.
3 / 24
Dynamic Programming (continued)
Iterative algorithm: (Running time: O(n))
1. A[0] = 0; A[1] = 1
2. for i = 2 to n do
A[i] = A[i-1] + A[i-2]
Matrix-Chain Multiplication:
4 / 24
Matrix-Chain Multiplication (continued)
A: r × 2 B: 2 × r C: r × 1
5 / 24
Matrix-Chain Multiplication (continued)
Recall: A: r × 2 B: 2 × r C: r × 1
6 / 24
Matrix-Chain Multiplication (continued)
Recall: A: r × 2 B: 2 × r C: r × 1
Summary:
Methods I and II use 3r 2 and 4r multiplications respectively.
Method II is better.
7 / 24
Matrix-Chain Multiplication (continued)
8 / 24
Matrix-Chain Multiplication (continued)
9 / 24
Matrix-Chain Multiplication (continued)
Recall: The last step computes the product M = M1 M2 where
M1 = A1 A2 · · · Ak and M2 = Ak+1 Ak+2 · · · An
for some k in the range 1 to n − 1.
11 / 24
Matrix-Chain Multiplication (continued)
Computing entries of M: Suppose we want to compute M[i, j]
for some i < j.
Consider all possible values k where the subchain
Ai Ai+1 · · · Aj can be split. Thus, i ≤ k ≤ j − 1.
If the split is at k, the following costs are involved:
1 M[i, k] for evaluating the subchain Ai · · · Ak .
2 M[k + 1, j] for evaluating the subchain Ak+1 · · · Aj .
3 Cost pi−1 pk pj to multiply the two matrices resulting from
1 and 2 above.
12 / 24
Matrix-Chain Multiplication (continued)
13 / 24
Matrix-Chain Multiplication (continued)
14 / 24
Matrix-Chain Multiplication (continued)
Pseudocode: See Handout 1.1. (A numerical example will be
presented in class.)
16 / 24
Dynamic Programming for a 1-Dimensional Problem
17 / 24
Maximum Subarray Sum Problem (continued)
Approach:
No. of subproblems = n.
Computation Steps:
B[1] = x1 .
To compute B[i + 1] for 1 ≤ i ≤ n − 1:
B[i + 1] = B[i] + xi+1 if B[i] > 0
= xi+1 otherwise.
Solution is the largest value in B.
18 / 24
Maximum Subarray Sum Problem (continued)
19 / 24
Subset Sum Problem: Definition
20 / 24
A Dynamic Programming Algorithm for Subset Sum
Approach:
21 / 24
Algorithm for Subset Sum (continued)
Computation Steps:
Running time:
23 / 24
Algorithm for Subset Sum (continued)
Space:
√
Fastest known algorithm: O( n (log n)c B) due to Koiliaris and
Xu, July 2015. (Here c is a constant.)
24 / 24