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?- A. 24
- B. 6
- C. 8
- 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
- Problem: How many islands (4-connected groups of '1') are in the grid below? Run the DFS code. python g = ['11000', '11000', '00100'…
- Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code. python from collections import Counter a =…
- Problem: A data stream needs the median of the last k elements. Which structure supports each slide in O(log k) time?
- Problem: Consider a connected undirected graph whose edge weights are all distinct. Which statement is true?
- Problem: What is the standard time complexity of bitmask DP for the travelling salesman problem on n cities?
- Array a = [3, -1, 2, 6, -4, 5, 1, -2]. How many non-empty contiguous subarrays have a sum divisible by 4?