ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (Kadane's maximum subarray sum)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (Kadane's maximum subarray sum)? (Arrays are indexed from 0.)
Integer arr[9] = {-2, 1, -3, 4, -1, 2, 1, -5, 4}
Integer maxEnd = arr[0], maxSoFar = arr[0]
for (each i from 1 to length(arr) - 1)
    maxEnd = max(arr[i], maxEnd + arr[i])
    maxSoFar = max(maxSoFar, maxEnd)
end for
Print maxSoFar
  1. A. 6
  2. B. 7
  3. C. 4
  4. D. 10

Correct answer: A. 6

This is Kadane's algorithm. The best contiguous subarray here is {4, -1, 2, 1}, summing to 6, which the running maxEnd/maxSoFar tracking correctly identifies as the overall maximum.

More Pseudocode and Code Tracing questions

Exams that ask this topic