Largest product of a contiguous run: track the high and the low at each step, because a negative number swaps them.
▼The problem
LeetCode 152 (Medium). Given an integer array nums, return the largest product of a contiguous, non-empty subarray.
Example (LeetCode's): [2,3,-2,4] → 6 (the piece [2,3]; the whole array is -48, because the -2 flips the sign).
The solution
def max_product(nums):
best = hi = lo = nums[0]
for x in nums[1:]:
cands = (x, x * hi, x * lo)
hi, lo = max(cands), min(cands)
best = max(best, hi)
return bestTranscript
Maximum Product Subarray. You get an array of integers. Find the contiguous, non-empty piece whose numbers multiply to the largest product, and return that product.
Take two, three, minus two, four. The whole array multiplies to minus forty eight, because the minus two flips the sign. The best piece is two times three: six.
The direct way tries every subarray and multiplies it. Four numbers already make ten subarrays, and n numbers make about n squared over two. That's order n squared.
Maximum Subarray does sums in one pass with Kadane: at each number, keep the best value of a piece ending there. Try that with products on minus two, three, minus four. The best ending here goes minus two, then three, then minus four, so it reports three. But the whole array makes twenty four! The piece ending at three with the smallest product, minus six, became the largest when minus four flipped it.
So keep two numbers: the highest and the lowest product ending here. For each x, the new high is the largest of x, x times high, and x times low. The new low is the smallest. A negative x swaps their roles. And a zero resets both to zero, so the next number starts fresh.
In code, high, low and best start at the first number. For each next x, build the three candidates. Their max becomes high, their min becomes low, and best keeps the largest high.
Back to two, three, minus two, four. We start at two. Three makes the high six, so best is six. Minus two swaps them: high minus two, low minus twelve. Four makes the high four and the low minus forty eight. Best stays six. Now add minus one to the end. It flips the low: minus forty eight becomes forty eight, the whole array and the new best.
One pass and three running numbers: order n time and order one space.
Track the high, track the low, and let negatives swap them. That's Maximum Product Subarray.