QuestionsDSA

Maximum Product Subarray

Dynamic Programming (running extremes)MediumDSA

Given an integer array, return the maximum product of any contiguous non-empty subarray. e.g. [2,3,-2,4] → 6, [-2,3,-4] → 24.

What it tests

Realising why Kadane's single running max fails for products, and carrying BOTH a running max and running min because a negative flips them.

Approach & answer

Products break the pure Kadane template, because multiplying by a negative turns the smallest (most negative) running value into the largest. So track a pair at each index: maxHere = best product ending here, minHere = worst (most negative) product ending here. For each number x the candidates are x alone, maxHere*x, and minHere*x; the new max is the largest of the three and the new min is the smallest. When x is negative this naturally lets a previous min become the new max. Keep a global best. This is the 'Kadane with sign-tracking' variant — the recognition signal is a running-subarray optimum where the combining operation is not monotonic (products, or sign changes), so one running extreme is not enough; carry both extremes. O(n) time, O(1) space.

Use this technique when

Best contiguous-subarray value where a single running extreme can be flipped (products, sign changes) → carry both the running max and running min and recombine each step.

Complexity

Time O(n) · Space O(1)

References

js