Maximum-Sum Contiguous Subsequence
A contiguous subsequence of a list is a subsequence made up of consecutive elements. For instance, if the list is 5, 15, −30, 10, −5, 40, 10, then 15, −30, 10 is a contiguous subsequence but 5, 15, 40 is not. Design a dynamic-programming algorithm for the following task.
The "includes a[i]" constraint is what makes this a prefix problem: forcing the segment to end at i lets each entry extend the previous one in O(1).
Either extend the best segment ending at i−1, or drop it and start fresh at a[i] (the max{0, …} branch). Defining T(0)=0 makes T(1)=a[1] fall out correctly — consistent with the "ends at a[i]" definition, which forces every T(i) to contain a[i].
Extraction must be max{ maxi T(i), 0 } — not plain max{T(*)}. Because the subproblem forces each segment to include a[i], every table entry holds at least one element. On an all-negative array, max{T(*)} returns the least-negative element; the empty-subsequence clause requires 0. The explicit , 0 is the fix.
Because entries are pinned to end at i, the best overall segment can end anywhere, so you take the max over all i. Same reasoning as LIS. Contrast LCS, where the answer is simply T(n,m).
Optional pseudocode not required by Ed #9
A mechanical translation of the recurrence. The exam grades the recurrence, not this — but here's the fill loop if you want it.
function MaxSubarray(a[1..n]): T[0] = 0 best = 0 for i = 1 to n: T[i] = a[i] + max(0, T[i-1]) best = max(best, T[i]) return best # = max{ max_i T(i), 0 }
Try it yourself
worked example + self-testRecurrence: T(0)=0; T(i)=a[i]+max{0,T(i-1)}. Answer max{maxi T(i), 0}.
a = [ 5, 15, −30, 10, −5, 40, 10 ] (1-indexed)
a[4..7] = [10, −5, 40, 10] (10−5+40+10 = 55).a = [ −2, −5, 6, −2, −3, 1, 5, −6 ] (leading-negative run — the max{0,·} clamp resets it)
Reveal answer
[6, −2, −3, 1, 5] = a[3..7]. Bonus edge: for an all-negative array like [−3,−1,−4,−2] the answer is 0 (empty subsequence wins).