Given an integer array nums, look at every subarray: a run of one or more neighbouring elements. Multiply the elements of each one together, and return the largest product you find.
A subarray of a single element has that element as its product. Negative numbers matter here: two of them multiply to a positive, so a run that looks bad halfway through can end up the best.
The whole array multiplies to (-2) · 3 · (-4) = 24. Each negative on its own drags the product down, but together they cancel out.
Any subarray that crosses the 0 has product 0, so the best is [5,2], giving 10. Left of the zero, the best is just 3.
The only subarray is [-5], so the answer is negative.
Constraints
1 <= nums.length <= 2 · 10⁴-10 <= nums[i] <= 10nums fits in a 32-bit signed integer.A negative number flips the sign of a product, so the smallest (most negative) product so far can become the largest one step later. A zero cuts the array: no useful run crosses it.
With sums, a run that has gone negative is dead weight, and you drop it. Products don't work that way. A run whose product is very negative is one negative number away from being very positive. In Example 1, -2 · 3 = -6 looks like the worst run so far, and one step later -6 · -4 = 24 is the answer.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium
24