Data Structures & AlgorithmsVery hardProduct Company SDE · DP round

Problem: What is the maximum product of a non-empty contiguous subarray of [2, 3, -2, 4, -1]? Use the code below.

Problem: What is the maximum product of a non-empty contiguous subarray of [2, 3, -2, 4, -1]? Use the code below.
a = [2, 3, -2, 4, -1]
mx = mn = ans = a[0]
for x in a[1:]:
    cands = (x, mx * x, mn * x)
    mx = max(cands)
    mn = min(cands)
    ans = max(ans, mx)
print(ans)
What is printed?
  1. A. 24
  2. B. 6
  3. C. 8
  4. D. 48

Correct answer: D. 48

The whole array has two negative values, so its product 2*3*(-2)*4*(-1) = 48 is the maximum. Tracking only the running maximum fails because a negative can flip the sign of the minimum.

More Coding Interview Problems questions

Exams that ask this topic