Data Structures & AlgorithmsModerateTCS NQT · Infosys

A maximum subarray sum routine is written as follows.

A maximum subarray sum routine is written as follows.
def best_sub(a):
    cur = best = a[0]
    for x in a[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best
print(best_sub([-5, -2, -9, -1, -4]))
What is printed?
  1. A. 0
  2. B. -1
  3. C. -21
  4. D. -2

Correct answer: B. -1

Initialising the answer to 0 is the classic bug: it returns 0 (the empty subarray) when every element is negative, but the problem requires a non-empty subarray, so the true answer is the largest single element, −1.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic