Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Maximum product of a contiguous subarray (values may be negative or zero).

Problem: Maximum product of a contiguous subarray (values may be negative or zero).
def maxprod(a):
    hi = lo = best = a[0]
    for x in a[1:]:
        if x < 0: hi, lo = lo, hi
        hi = max(x, hi * x); lo = min(x, lo * x)
        best = max(best, hi)
    return best
print(maxprod([-2, 3, -4, 0, 5, -1, 2]))
What is printed?
  1. A. 5
  2. B. 12
  3. C. 3
  4. D. 24

Correct answer: D. 24

Keep both the largest and smallest product ending here, since a negative number swaps them. −2 × 3 × −4 = 24 beats anything after the zero (5, or 5 × −1 × 2 = −10). Kadane on sums would give 5.

More Coding Interview Problems questions

Exams that ask this topic