04-class
04-class
Two examples of divide-and-conquer: 4.1, 4.2 (2) compute each S[i, j+1] from S[i, j] in O(1) time
Solving recurrences: 4.3, 4.4, 4.5 (S[i, i] = A[i] and S[i, j+1] = S[i, j] + A[j+1])
O(n2) time
(ex. S[2, 12] = S[2, 11] + A[12])
4.1 The maximum-subarray problem
i=2
i 1 2 3 4 5 6 7 8 9 10 11 12 13
Input: an array A[1..n] of n numbers
A[i] 13 -15 23 4 -13 -16 -23 18 20 -7 12 -5 -22
Output: a nonempty subarray A[i..j] having S[2, 2] = -15
the largest sum S[i, j] = ai + ai+1 +... + aj S[2, 3] = 8
S[2, 4] = 12
S[2, 5] = -1 O(n) time for each i
20 18
A divide-and-conquer solution
goal
with T(0) = c = Θ(1)
Try to prove T(n) cn – b. (for n n0) Example: T(n) = 3T(n/4) + n
T(1) = c = Θ(1)
Induction: T(n) (cn/2-b) + (cn/2 -b) + 1 T(x)= x + 3T(x/4)
4-14y
T(1) T(0) . . . . . . . .
4-15a