ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
best = cur = a[0]
for x in a[1:]:
    cur = max(x, cur + x)
    best = max(best, cur)
print(best)
  1. A. 4
  2. B. 6
  3. C. 12
  4. D. 1

Correct answer: B. 6

Kadane keeps the best sum of a subarray ending at the current index; the best run 4, −1, 2, 1 sums to 6. 4 is the largest single element, 12 adds every positive, and 1 is the whole-array sum.

More Python Programming questions

Exams that ask this topic