You get a list of whole numbers, nums. A subarray is a run of one or more neighbouring elements. Find the subarray whose elements multiply to the largest product, and return that product.
A subarray of a single element has that element as its product. Every product you could form fits in a 32-bit signed integer.
Example 1
Input: nums = [2, -5, -2, -4, 3] Output: 24 Why: -2 × -4 × 3 = 24
2 more examples and the constraints
Example 2
Input: nums = [-4, 0, -3, -1] Output: 3 Why: -3 × -1 = 3; the 0 cuts off the -4
Example 3
Input: nums = [-6] Output: -6 Why: the only subarray is [-6]
Constraints
- 1 ≤ length of nums ≤ 20,000
- Every number is between −10 and 10
- The product of any subarray fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(n²)
- Running max and minO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 numbers | Verdict |
|---|---|---|---|
| Brute force | O(n²) | Mention it, then move on | |
| Running max and min | O(n) | Best; one pass |
n = how many numbers are in the list.
Edge cases to test
- Single negative number. [-6] returns -6. Do not start best at 0.
- Zeros. [-4, 0, -3, -1]: a zero splits the list, and 0 itself can be the answer, as in [-3, 0, 0, -5].
- Odd number of negatives. [-1, -1, -1]: the best uses two of them, giving 1.
- Two negatives only. [-2, -3] gives 6, the whole list.
Common mistakes
- Keeping only the running maximum, which loses the very negative product that one more negative would flip.
- Updating hi and then using the new hi to compute lo.
- Starting best at 0, which is wrong when every number is negative and there is no zero.
How to talk through it
- 1Clarify. Must the subarray be non-empty? Can there be zeros? Can the product overflow?
- 2Give the brute force. Every start, running product to every end: O(n²).
- 3Name the twist. Kadane fails because a negative swaps the best and the worst, so track both.
- 4Code the one pass. Compute both candidates from the old hi and lo, then update best.
- 5Test out loud. Run [-6], a list with a zero, and [-1, -1, -1].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?