Largest Product of Any Contiguous Subarray

Implement maxProductSubarray

Given an array nums that may contain negative numbers and zeros, find the largest product achievable by any non-empty contiguous subarray. The tricky part is negatives: a very negative running product can flip into the best possible product the moment it's multiplied by another negative. Plain Kadane's algorithm only tracks a running maximum — here you need to also track a running minimum, since today's worst product might become tomorrow's best one. Whenever the next number is negative, swap the running max and min before extending them — that's what makes the O(n) Kadane's AlgorithmKadane's AlgorithmA single-pass dynamic programming technique that extends or restarts a running best-so-far value at each position, avoiding the need to re-examine every subarray from scratch. variant work for products instead of just sums.

Example 1:

Input: nums = [-2,3,-4]

Output: 24

Example 2:

Input: nums = [2,3,-2,4]

Output: 6

Example 3:

Input: nums = [0,2]

Output: 2

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 2×10⁴
  • -10 ≤ nums[i] ≤ 10

nums =

[-2, 3, -4]