Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

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

Problem: Return the 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:]:
        cand = (x, hi * x, lo * x)
        hi, lo = max(cand), min(cand)
        best = max(best, hi)
    return best
print(maxprod([2, 3, -2, 4]), maxprod([-2, 3, -4]), maxprod([-2, 0, -1]))
What is printed?
  1. A. 8 24 0
  2. B. 6 12 0
  3. C. 6 24 0
  4. D. 6 24 -1

Correct answer: C. 6 24 0

Track both the largest and the smallest product ending here, because a negative number turns the smallest into the largest. [−2, 3, −4] → whole array 24. With zeros the best can be 0. Kadane on sums alone gives the wrong 12 or 3. O(n).

More Coding Interview Problems questions

Exams that ask this topic