Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed).
Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed).
def best_k(a, k):
s = best = sum(a[:k])
for i in range(k, len(a)):
s += a[i] - a[i - k]; best = max(best, s)
return best
def best_circ(a):
cur_max = cur_min = 0; mx, mn = a[0], a[0]
for x in a:
cur_max = max(x, cur_max + x); mx = max(mx, cur_max)
cur_min = min(x, cur_min + x); mn = min(mn, cur_min)
return mx if mx < 0 else max(mx, sum(a) - mn)
print(best_k([1, 4, 2, 10, 23, 3, 1, 0, 20], 4), best_circ([5, -3, 5]), best_circ([-3, -2, -3]))What is printed?- A. 39 7 -2
- B. 36 10 -2
- C. 39 10 -8
- D. 39 10 -2
Correct answer: D. 39 10 -2
Fixed window: slide and update the sum in O(1): 4 + 2 + 10 + 23 = 39. Circular: the best wrap-around subarray is total − (minimum subarray): 7 − (−3) = 10. If every value is negative, total − min would be the empty subarray (0), so return the plain maximum −2 instead. O(n).
More Coding Interview Problems questions
- Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed). cpp int n = 8; vector<long long> t(n + 1, 0); void…
- Problem: Range minimum queries with a sparse table after O(n log n) preprocessing. python a = [7, 2, 9, 4, 3, 8, 6, 1, 5] n = len(a); LOG…
- Problem: A segment tree stores range sums. How many nodes does the recursive query visit? python a = [1, 3, 5, 7, 9, 11, 13, 15] visits =…
- Problem: Count the board states reachable on a 2 × 2 sliding puzzle ('0' is the blank, which swaps with an adjacent tile), using BFS over…
- Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people. python def…
- Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order). python def redundant(edges)…