The max-product scan returns the largest subarray product full
This proof shows: correctness.
We use the pseudocode of the page on A[0..n−1] with n≥1. For i≤j let Π(i,j)=A[i]⋯A[j]. For each j let Xj={Π(i,j):0≤i≤j}, the products of the subarrays ending at j, and let E+(j)=maxXj, E−(j)=minXj and B(j)=max0≤i≤l≤jΠ(i,l).
Lemma 1. For j≥1, Xj={A[j]}∪{x⋅A[j]:x∈Xj−1}.
Proof. Π(j,j)=A[j], and Π(i,j)=Π(i,j−1)⋅A[j] for i<j. ■
Lemma 2. For j≥1, let (u,v)=(E+(j−1),E−(j−1)) if A[j]≥0 and (u,v)=(E−(j−1),E+(j−1)) if A[j]<0. Then E+(j)=max(A[j],uA[j]) and E−(j)=min(A[j],vA[j]).
Proof. Every x∈Xj−1 has E−(j−1)≤x≤E+(j−1). If A[j]≥0, then xA[j]≤E+(j−1)A[j] and xA[j]≥E−(j−1)A[j]. If A[j]<0, multiplying by A[j] reverses the inequalities, so xA[j]≤E−(j−1)A[j] and xA[j]≥E+(j−1)A[j]. In both cases uA[j] is the largest and vA[j] the smallest element of {xA[j]:x∈Xj−1}, and both occur, since E+(j−1) and E−(j−1) are elements of Xj−1. Lemma 1 completes the proof. ■
Claim. After step j (after line L1 for j=0, after line L6 for j≥1), hi=E+(j), lo=E−(j) and best=B(j).
Proof. By induction on j.
Base. X0={A[0]}, so E+(0)=E−(0)=B(0)=A[0], which line L1 sets.
Step, j≥1. Before line L3, hi=E+(j−1) and lo=E−(j−1) by induction. After line L3, (hi,lo)=(u,v) as in Lemma 2. Line L4 sets hi=max(A[j],uA[j])=E+(j). Line L5 uses lo=v, which line L4 did not change, and sets lo=min(A[j],vA[j])=E−(j). A subarray of A[0..j] either ends at j or lies in A[0..j−1], so B(j)=max(B(j−1),E+(j)), which line L6 computes from best=B(j−1). ■
Theorem. MAX-PRODUCT returns B(n−1), the largest product of a non-empty subarray of A.
Proof. Apply the claim with j=n−1. The loop runs n−1 times with O(1) arithmetic operations each, so the algorithm stops. ■