Maximum Product in Contiguous ArrayLoading saved progress…

Maximum Product in Contiguous Array

Given an array of integers, find the contiguous (non-empty) run of elements whose product is the largest, and return that product. A contiguous run means you pick a start and an end index and take everything in between — no skipping, no reordering. This is the multiplication cousin of the well-known maximum subarray (Kadane's) problem, but multiplication changes the rules: two negatives can multiply into a large positive, and a single zero wipes a product out. You only return the product — not the subarray itself.

Signature

// nums: number[] — a non-empty array of integers (may include negatives and zeros).
// returns: number — the maximum product over every contiguous, non-empty subarray.
function arrayMaximumProductContiguous(nums: number[]): number;

Examples

// The positive run [2, 3] beats the lone 4. The -2 breaks the array in two.
arrayMaximumProductContiguous([2, 3, -2, 4]); // → 6
// Two negatives cancel: -2 * 3 * -4 = 24 over the whole array.
arrayMaximumProductContiguous([-2, 3, -4]); // → 24
// Every subarray here is <= 0, and the 0 itself is the largest reachable product.
arrayMaximumProductContiguous([-2, 0, -1]); // → 0
// Four negatives: drop one end to keep an even count → [-2, -4, 3] = 24.
arrayMaximumProductContiguous([2, -5, -2, -4, 3]); // → 24

Notes

  • Negatives flip sign. A negative times the smallest-so-far product can become the new largest — so tracking only a running maximum is not enough. You also have to track the running minimum.
  • Zeros reset. A zero makes any product through it zero, so the best run never spans a zero. After a zero, you start fresh from the next element.
  • The subarray must be non-empty. The empty product (1) is not a valid answer; with [-5] the answer is -5, not 1 or 0.
  • Single element is valid. A subarray of length one is contiguous, so an all-negative array like [-2, -3, -4] can answer with a single element (-2) when no even-length run beats it.
  • Don't worry about returning the indices or the subarray itself, overflow (treat numbers as exact), or empty-array input — nums always has at least one element.
Loading editor…