Algorithm Search⌘K

Proofs: Max-product scan with minimum tracking

These are the human proofs of Max-product scan with minimum tracking, at full length.

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]A[0..n-1] with n≥1n \ge 1. For i≤ji \le j let Π(i,j)=A[i]⋯A[j]\Pi(i, j) = A[i] \cdots A[j]. For each jj let Xj={Π(i,j):0≤i≤j}X_j = \{\Pi(i, j) : 0 \le i \le j\}, the products of the subarrays ending at jj, and let E+(j)=max⁡XjE^{+}(j) = \max X_j, E−(j)=min⁡XjE^{-}(j) = \min X_j and B(j)=max⁡0≤i≤l≤jΠ(i,l)B(j) = \max_{0 \le i \le l \le j} \Pi(i, l).

Lemma 1. For j≥1j \ge 1, Xj={A[j]}∪{x⋅A[j]:x∈Xj−1}X_j = \{A[j]\} \cup \{x \cdot A[j] : x \in X_{j-1}\}.

Proof. Π(j,j)=A[j]\Pi(j, j) = A[j], and Π(i,j)=Π(i,j−1)⋅A[j]\Pi(i, j) = \Pi(i, j-1) \cdot A[j] for i<ji < j. ■\blacksquare

Lemma 2. For j≥1j \ge 1, let (u,v)=(E+(j−1),E−(j−1))(u, v) = (E^{+}(j-1), E^{-}(j-1)) if A[j]≥0A[j] \ge 0 and (u,v)=(E−(j−1),E+(j−1))(u, v) = (E^{-}(j-1), E^{+}(j-1)) if A[j]<0A[j] < 0. Then E+(j)=max⁡(A[j],uA[j])E^{+}(j) = \max(A[j], u A[j]) and E−(j)=min⁡(A[j],vA[j])E^{-}(j) = \min(A[j], v A[j]).

Proof. Every x∈Xj−1x \in X_{j-1} has E−(j−1)≤x≤E+(j−1)E^{-}(j-1) \le x \le E^{+}(j-1). If A[j]≥0A[j] \ge 0, then xA[j]≤E+(j−1)A[j]x A[j] \le E^{+}(j-1) A[j] and xA[j]≥E−(j−1)A[j]x A[j] \ge E^{-}(j-1) A[j]. If A[j]<0A[j] < 0, multiplying by A[j]A[j] reverses the inequalities, so xA[j]≤E−(j−1)A[j]x A[j] \le E^{-}(j-1) A[j] and xA[j]≥E+(j−1)A[j]x A[j] \ge E^{+}(j-1) A[j]. In both cases uA[j]u A[j] is the largest and vA[j]v A[j] the smallest element of {xA[j]:x∈Xj−1}\{x A[j] : x \in X_{j-1}\}, and both occur, since E+(j−1)E^{+}(j-1) and E−(j−1)E^{-}(j-1) are elements of Xj−1X_{j-1}. Lemma 1 completes the proof. ■\blacksquare

Claim. After step jj (after line L1 for j=0j = 0, after line L6 for j≥1j \ge 1), hi=E+(j)hi = E^{+}(j), lo=E−(j)lo = E^{-}(j) and best=B(j)best = B(j).

Proof. By induction on jj.

Base. X0={A[0]}X_0 = \{A[0]\}, so E+(0)=E−(0)=B(0)=A[0]E^{+}(0) = E^{-}(0) = B(0) = A[0], which line L1 sets.

Step, j≥1j \ge 1. Before line L3, hi=E+(j−1)hi = E^{+}(j-1) and lo=E−(j−1)lo = E^{-}(j-1) by induction. After line L3, (hi,lo)=(u,v)(hi, lo) = (u, v) as in Lemma 2. Line L4 sets hi=max⁡(A[j],uA[j])=E+(j)hi = \max(A[j], u A[j]) = E^{+}(j). Line L5 uses lo=vlo = v, which line L4 did not change, and sets lo=min⁡(A[j],vA[j])=E−(j)lo = \min(A[j], v A[j]) = E^{-}(j). A subarray of A[0..j]A[0..j] either ends at jj or lies in A[0..j−1]A[0..j-1], so B(j)=max⁡(B(j−1),E+(j))B(j) = \max(B(j-1), E^{+}(j)), which line L6 computes from best=B(j−1)best = B(j-1). ■\blacksquare

Theorem. MAX-PRODUCT returns B(n−1)B(n-1), the largest product of a non-empty subarray of AA.

Proof. Apply the claim with j=n−1j = n - 1. The loop runs n−1n - 1 times with O(1)O(1) arithmetic operations each, so the algorithm stops. ■\blacksquare

Back to Max-product scan with minimum tracking