Data Structures & AlgorithmsHardGoldman Sachs OA · LeetCode medium-hard
Problem: Find the maximum sum of a non-empty subarray of a CIRCULAR array (a subarray may wrap from the end to the start).
Problem: Find the maximum sum of a non-empty subarray of a CIRCULAR array (a subarray may wrap from the end to the start).
def f(a):
best = cur = a[0]; worst = cur2 = a[0]
for x in a[1:]:
cur = max(x, cur + x); best = max(best, cur)
cur2 = min(x, cur2 + x); worst = min(worst, cur2)
if best < 0:
return best
return max(best, sum(a) - worst)
print(f([8, -1, -3, 8, -6, -5, 7]), f([-4, -2, -7]))What is printed?- A. 19 0
- B. 19 -2
- C. 12 -2
- D. 12 0
Correct answer: B. 19 -2
The best wrapping subarray is the total (8) minus the minimum subarray (−6 − 5 = −11), i.e. 7 + 8 − 1 − 3 + 8 = 19, beating the plain Kadane value 12. When every value is negative, total − min would be 0 (an empty subarray), so the guard returns the largest element, −2.
More Coding Interview Problems questions
- Problem: Install c routers at some of the given highway mile-markers so that the smallest distance between any two routers is as LARGE as…
- A divide-and-conquer routine satisfies T(n) = 4T(n/2) + n² log n. What is its running time?
- Edge case: A helper collects items into a list using a default argument. python def collect(x, out=[]): out.append(x) return out a =…
- Problem: n servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined…
- Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next. python import heapq…
- Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale…