April 8, 2003 Algorithm design paradigms ========================== Consider the following array. You are given a large array X of integers (both positive and negative) and you need to find the maximum sum found in any contiguous subarray of X. Applications in graphics and pattern recognitions. Example X = [11, -12, 15, -3, 8, -9, 1, 8, 10, -2] Answer is 30. Solution 1: Brute force maxSum = 0 for L = 1 to N { for R = L to N { sum = 0 for i = L to R { sum = sum + X[i] } maxSum = max(maxSum, sum) } } O(N^3) Solution 2: Quadratic Note that sum of [L..R] can be calculated from sum of [L..R-1] very easily. maxSum = 0 for L = 1 to N { sum = 0 for R = L to N { sum = sum + X[R] maxSum = max(maxSum, sum) } } Solution 3: Using divide-and-conquer O(N log(N)) maxSum(L, R) { if L > R then return 0 if L = R then return max(0, X[L]) M = (L + R)/2 sum = 0; maxToLeft = 0 for i = M downto L do { sum = sum + X[i] maxToLeft = max(maxToLeft, sum) } sum = 0; maxToRight = 0 for i = M to R do { sum = sum + X[i] maxToRight = max(maxToRight, sum) } maxCrossing = maxLeft + maxRight maxInA = maxSum(L,M) maxInB = maxSum(M+1,R) return max(maxCrossing, maxInA, maxInB) } Solution 4: The scanning algorithm covered in class O(N) maxSum = 0 maxEndingHere = 0 for i = 1 to N do { maxEndingHere = max(maxEndingHere + X[i], 0) maxSum = max(maxSum, maxEndingHere) } return max