ProgrammingHardTCS NQT · Accenture

Array a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Kadane's algorithm below finds the maximum sum of a non-empty contiguous subarray. What is printed?

Array a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Kadane's algorithm below finds the maximum sum of a non-empty contiguous subarray. What is printed?
cur = a[0]; best = a[0]
for i = 1 to n - 1
    cur = max(a[i], cur + a[i])
    best = max(best, cur)
end for
Print best
  1. A. 6
  2. B. 4
  3. C. 1
  4. D. 2

Correct answer: A. 6

Kadane restarts the running sum whenever it goes negative, and the best run is 4, -1, 2, 1, which sums to 6. The largest single element gives 4, the total sum gives 1, and a running sum that never restarts gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic