The circular Kadane algorithm returns the best circular subarray sum full
This proof shows: correctness.
We use the pseudocode of the page on A[0..n−1] with n≥1. Write S(i,j)=A[i]+⋯+A[j] for i≤j, and S(i,i−1)=0. Let T=S(0,n−1). A plain subarray is a pair (i,j) with 0≤i≤j≤n−1, with sum S(i,j). A wrapping subarray is a pair (i,j) with 0≤j<i≤n−1, with sum W(i,j)=S(i,n−1)+S(0,j). Let Smax∗ and Smin∗ be the largest and smallest plain sums, and C∗ the largest sum over plain and wrapping subarrays.
Lemma 1 (the scans). After the loop, best=Smax∗, worst=Smin∗ and T=S(0,n−1).
Proof. Line L3 is the recurrence E(j)=A[j]+max(E(j−1),0) of Kadane's algorithm together with the running maximum of E, so the invariant of that algorithm gives best=Smax∗. Line L4 is the same recurrence for B=−A, with every value negated: if hi′ and best′ are the values of line L3 on B, then lo=−hi′ and worst=−best′ at each step, by induction on j, because −(B[j]+max(x,0))=A[j]+min(−x,0). So worst=−max(plain sums of B)=Smin∗. Line L5 adds each item once. ■
Lemma 2 (complement). For a wrapping subarray (i,j), W(i,j)=T−S(j+1,i−1). The map (i,j)↦(j+1,i−1) is a bijection from wrapping subarrays to the blocks (a,b) with 1≤a≤b+1≤n−1, that is, to the plain subarrays that contain neither A[0] nor A[n−1], together with the empty blocks (a,a−1) for 1≤a≤n−1.
Proof. The items 0..n−1 split into 0..j, j+1..i−1 and i..n−1, so T=S(0,j)+S(j+1,i−1)+S(i,n−1). The inverse map is (a,b)↦(b+1,a−1), and the conditions 0≤j<i≤n−1 match 1≤a≤b+1≤n−1. ■
Lemma 3. Every wrapping sum is at most max(T−Smin∗,T), and T≤Smax∗. Also, if Smin∗ is reached by a plain block (a,b) other than the whole array, then some circular subarray has sum T−Smin∗.
Proof. By Lemma 2 a wrapping sum is T−S(a,b) for a block that is either a plain subarray, so S(a,b)≥Smin∗, or empty, so the sum is T. And T=S(0,n−1)≤Smax∗. For the second part, let (a,b)=(0,n−1) reach Smin∗. If 1≤a and b≤n−2, Lemma 2 gives a wrapping subarray with sum T−S(a,b). If a=0, then b≤n−2 and the plain subarray (b+1,n−1) has sum T−S(0,b). If b=n−1, then a≥1 and the plain subarray (0,a−1) has sum T−S(a,n−1). ■
Theorem. CIRCULAR-KADANE returns C∗.
Proof. By Lemma 1, best=Smax∗ and worst=Smin∗.
Case best<0. Every item is negative, because a single item is a plain subarray. A circular subarray contains some item A[k], and its other items are negative, so its sum is at most A[k]≤Smax∗. Plain subarrays reach Smax∗, so C∗=Smax∗, which line L6 returns.
Case best≥0. By Lemma 3 every wrapping sum is at most max(T−Smin∗,Smax∗), and every plain sum is at most Smax∗. So C∗≤max(Smax∗,T−Smin∗). For the other direction, Smax∗ is reached by a plain subarray. If Smin∗ is reached by a block other than the whole array, Lemma 3 gives a circular subarray with sum T−Smin∗. Otherwise Smin∗=T and T−Smin∗=0≤best. In both cases max(Smax∗,T−Smin∗)≤C∗. So line L7 returns C∗.
Termination. The loop runs n−1 times with O(1) work per step. ■