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?- A. 5
- B. 12
- C. 3
- 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
- Problem: Taking a value v earns v points for EVERY copy of v, but then all copies of v − 1 and v + 1 are deleted. Maximise the points…
- Problem: Travel on given days; passes cost costs[0] (1 day), costs[1] (7 days) and costs[2] (30 days). Minimise the total cost. python def…
- Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed. python def robline(a): take…
- Problem: Each person is [h, k]: height h, and exactly k people in front are at least as tall. Rebuild the queue (sort tallest first…
- Problem: 2n people must be split so n fly to city A and n to city B; costs[i] = [costA, costB]. Minimise total cost (sort by costA −…
- Problem: Can the cards be split into groups of W consecutive values? python from collections import Counter def straights(hand, W): if…