Algorithm Analysis Lakshmish Ramaswamy Maximum Contiguous Subsequence Problem
Algorithm Analysis Lakshmish Ramaswamy
Maximum Contiguous Subsequence • Problem: Given a sequence of (possibly negative) integers A 1, A 2, …, AN find the subsequence Ai, A(i+1), …, Aj such that Ai + A(i+1)+ … + Aj is maximum • If input {-2, 11, -4, 13, -5, 2} then answer is 20 • If all numbers are negative, the empty subsequence (sum = 0) is the answer
Simple Algorithm
Analysis • Four repeated tasks – Initialization k = I – Test k <= j – Increment this. Sum += a[k] – Adjustment k++ • Increment is the most frequently executed statement – Constant time per increment
Analysis • Number of times increment is executed equals triplets (i, j, k) such that 1 <=i <=k <=j <= N (or 0 <= i <= k <= j <= (N-1)) – When i = 0, j can range from 0 to (N-1), and for each value of j, k can range from 0 to j – Suppose N = 3 possible values of i, j, k are [(0, 0, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 2, 2)] – Number of tuples = N(N+1)(N+2)/6 • O(N 3) algorithm
Can the Algorithm be Improved? • Lots of duplicate computation • Observation - ∑k=ik=j. Ak = ∑k=ik=(j-1)Ak +Aj • Eliminate innermost loop by reusing results of previous iteration
A Better Algorithm
Analysis • Removing a loop generally lowers running time • Two loops • Number of times increment is executed equals pairs (i, j) such that 1 <=i <=j <= N (or 0 <= i <= j <= (N-1)) • Number of pairs = (N+1)(N+2)/2 • O(N 2) algorithm
Can Algorithm be Still Improved? • Observation – 1: For any subsequence Ai, j with Si, j < 0, for any q => j Ai, q cannot be the maximum contiguous subsequence
Observation - 2 • For any i, Ai, j be the first sequence with Si, j < 0. For any p & q such that i <=p <= j and p<=q, Ap, q either is not a maximum contiguous subsequence or is equal to an already seen maximum contiguous subsequence
Even Better Algorithm
Analysis • Single loop • Loop iterates at most N times – Each element of the array is involved in only one summation operation – At most N summation operations • O(N) algorithm
- Slides: 12