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?
  1. A. 19 0
  2. B. 19 -2
  3. C. 12 -2
  4. 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

Exams that ask this topic