Dynamic Programming
![Question 25, GATE 2019: For A=[−5,−10,6,3,−1,−2,13,4,−9,−1,4,12,−3,0], find the maximum S(i,j)=sum of A[k] for k=i through j, with 0≤i≤j<14. The chosen elements must form a contiguous segment.](../../assets/questions/CS-2019-Q35-1.webp)
Answer & solution
Official answer: 29
Method: use Kadane's dynamic program. Let E[j] be the largest sum of any nonempty segment ending exactly at j. Such a segment either starts at j or extends the best segment ending at j−1.
1. The recurrence is E[0]=A[0]=−5 and E[j]=max(A[j],E[j−1]+A[j]). It is exhaustive because every segment ending at j has one of those two forms.
2. At indices 0 and 1, E is −5 then max(−10,−15)=−10. At index 2, starting afresh with 6 beats extending the negative prefix, so E[2]=6 and the candidate segment starts at index 2.
3. Continue through indices 3 to 7: E values are 9,8,6,19,23. Although −1 and −2 reduce the running sum, discarding the accumulated positive prefix would be worse.
4. For indices 8 to 13 the values are 14,13,17,29,26,26. The maximum across all E values is 29, achieved at j=11.
5. Recover the segment from i=2 through j=11: 6+3−1−2+13+4−9−1+4+12=29. The negative terms inside it must remain because the segment is contiguous.
6. Since every segment has some ending index j and E[j] is optimal for that ending index, taking the largest E[j] proves that no omitted segment has a greater sum.
Result: 29. The prompt permits divide and conquer but does not require it; this linear-time recurrence gives the same optimum and a direct correctness argument.