Data Structures & AlgorithmsEasyProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative).

Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative).
def best(a):
    cur = ans = a[0]
    for x in a[1:]:
        cur = max(x, cur + x)
        ans = max(ans, cur)
    return ans
print(best([-3, -1, -4, -2]))
What is printed for this all-negative edge case?
  1. A. -1
  2. B. 0
  3. C. -10
  4. D. -3

Correct answer: A. -1

Kadane's algorithm keeps the best sum ending at each index. With all negatives, starting fresh at each element is better, and the answer is the largest single element, −1. A version that initialises cur and ans to 0 would wrongly print 0 (the empty block is not allowed). O(n).

More Coding Interview Problems questions

Exams that ask this topic