ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def kadane(a):
    best = cur = a[0]
    start = best_l = best_r = 0
    for i in range(1, len(a)):
        if cur < 0:
            cur = a[i]
            start = i
        else:
            cur += a[i]
        if cur > best:
            best = cur
            best_l, best_r = start, i
    return best, best_l, best_r
print(kadane([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
  1. A. (6, 2, 6)
  2. B. (4, 3, 3)
  3. C. (6, 3, 5)
  4. D. (6, 3, 6)

Correct answer: D. (6, 3, 6)

Kadane's rule restarts the running sum when it turns negative and records the bounds of the best sum. The best subarray is 4, -1, 2, 1 with sum 6, from index 3 to index 6.

More Python Programming questions

Exams that ask this topic