Example 1
- Input
- nums = [2, 3, -2, 4]
- Output
- 6
The contiguous block [2, 3] has product 6. Including -2 makes that product negative, and the best block after it is [4] with product 4, so the overall maximum remains 6.
Given an integer array, find the largest product of any contiguous non-empty subarray.
You are given an integer array nums. A subarray takes a contiguous non-empty block.
Return the maximum product over all such blocks. Negatives flip signs, so the best block may hold an even count of them, and zeros split the array into independent parts.
1 <= nums.length <= 2 * 10^4-10 <= nums[i] <= 10The contiguous block [2, 3] has product 6. Including -2 makes that product negative, and the best block after it is [4] with product 4, so the overall maximum remains 6.
The one-element block [0] beats both negative singletons. The two negatives cannot multiply to 2 without including the separating zero, which makes the product 0.
A subarray must be non-empty, so the only candidate is the lone negative value. Initializing the answer to zero would incorrectly allow an empty block.
The entire block has two negatives and product 24. Before the last value, the minimum ending product is -6; multiplying it by -4 produces the maximum. Keeping only the previous maximum 3 would miss 24.
Multiplication can reverse which partial result is useful: in [-2, 3, -4], the smallest product ending at 3 is -6, and the next -4 turns it into the largest product 24. Keep both the maximum and minimum products of non-empty subarrays ending at the current index, rather than only a global maximum. In Example 1, extending [2, 3] by -2 makes -12, so starting again at 4 beats extending that negative block, while the global answer stays 6. Zero makes both ending products zero; the next value can start a new block.
Reveal Check Every Subarray: intuition, complexity, and code
[-3] returns -3; skipping is impossible since blocks are non-empty.[-2, -3] multiply into the positive answer 6.[-2, 3, -4] shows.curMax before computing curMin feeds the new extreme into the old pair; use a temporary.When an update can invert order, carry both extremes forward: the minimum is the future maximum one sign flip away.