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?- A. 8 24 0
- B. 6 12 0
- C. 6 24 0
- 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
- Problem: Can an array be split into two subsets with equal sums? python def cansplit(a): s = sum(a) if s % 2: return False reach = 1 for x…
- Problem: Return the length of the longest palindromic subsequence (not substring). python def lps(s): n = len(s); dp = [[0] n for in…
- Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications…
- Problem: A DP solution for 'minimum coins for amount A using c denominations' with A ≤ 10⁴ and c ≤ 100 is accepted. A friend proposes…
- Problem: Find the largest square of 1s in a binary matrix and return its area. python def square(m): R, C = len(m), len(m[0]); dp = [[0]…
- Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit. python def cooldown(p): hold…