Goal
Given an integer array nums, find the contiguous subarray with the largest product and return that product.
Key Idea (Intuition)
For a subarray that ends at index i, any candidate product must arise from either extending a previously tracked sequence or starting fresh at nums[i]. We therefore maintain two running values for subarrays ending at the current index:
maxProduct— maximum product ending at the current indexminProduct— minimum product ending at the current index
When nums[i] < 0, multiplying by a negative reverses order: among the two extension options we must compare,
minProduct × nums[i] is greater than or equal to maxProduct × nums[i].
This reversal between the extension candidates is precisely why we maintain both the running maxProduct and minProduct at every step.
Initialization
maxProduct = nums[0]minProduct = nums[0]result = nums[0](global best so far)- Start traversal at
i = 1.
Traversal
For each index i from 1 to n - 1:
-
Form candidates for subarrays ending at
i:c1 = maxProduct × nums[i],c2 = minProduct × nums[i],c3 = nums[i]. -
Update per-index extremes:
maxProduct = max(c1, c2, c3);minProduct = min(c1, c2, c3). -
Update global best:
result = max(result, maxProduct).
Return
Return result as the maximum product of any contiguous subarray.