Professional Documents
Culture Documents
L2 version
1
Maximum Sum problem
Let A be a sequence of n positive numbers a1, a2, . . , an.
Find the subset S of A that has the maximum sum, provided that if we
select ai in S, then we cannot select ai-1 or ai+1.
2
Dynamic Programming solution
General idea:
Let Ai be the subsequence of A containing the first i numbers
(i n): a1, a2, . . . , ai
Let Si be the solution of problem Ai.
Let Wi be the sum of numbers in Si.
Cost: (n)
Example: for A= 1, 8, 6, 3, 7, we have
W[1] = 1, b[1] = 1
W[2] = 8, b[2] = 1
W[3] = 8, b[3] = 0
W[4] = 11, b[4] = 1
W[5] = 15, b[5] = 1
Printing the solution
i=n
while i > 0
if b[i] is true
Output ai
i = i2
else
i = i1
11-12
Recursive definition for optimal solution
Let m[i, j] be the minimum number of scalar multiplications
necessary to compute Ai..j
Suppose the optimal parenthesization of Ai..j splits the product
between Ak and Ak+1 for some integer k where i k < j
Ai..j = (Ai Ai+1Ak)(Ak+1Ak+2Aj)= Ai..k Ak+1..j
11-14
Example
The initial set of dimensions are <5, 4, 6, 2, 7.
We are multiplying A1 (5x4) x A2 (4x6) x A3 (6x2) x A4 (2x7).
Optimal sequence is (A1 (A2A3 )) A4.