Skip to content
BytePatterns

Largest Product Subarray

MediumArrays#kadane#running-min-max~25m

Problem

A growth model stores daily multipliers as integers, some negative and some zero. Given a non-empty list nums, return the largest product of any non-empty contiguous run of values. The list has up to 20,000 values between -10 and 10, and the answer fits in a normal integer. Checking every run is too slow.

Examples

Input:  nums = [2, 3, -2, 4]
Output: 6
Why:    the run [2, 3]; adding -2 flips the sign
Input:  nums = [-2, 3, -4]
Output: 24
Why:    two negatives cancel, so the whole list wins
Input:  nums = [-2, 0, -1]
Output: 0
Why:    edge case, a zero beats every run that holds a single negative

Hints

0 / 3

Stuck on the idea rather than the code? Kadane's Algorithm covers it.