ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode? (Arrays are indexed from 0.)

What will be the output of the following pseudocode? (Arrays are indexed from 0.)
Integer arr[6] = {5, -2, 3, -1, 4, -6}
Integer s = 0, m = 0
for (each i from 0 to 5)
    s = s + arr[i]
    if (s < 0)
        s = 0
    end if
    if (s > m)
        m = s
    end if
end for
Print m
  1. A. 12
  2. B. 3
  3. C. 5
  4. D. 9

Correct answer: D. 9

This is Kadane's algorithm. s runs 5, 3, 6, 5, 9, 3 and never drops below 0, so it is never reset. The maximum is 9 (5 - 2 + 3 - 1 + 4). The total of all elements, 3, is the trap.

More Pseudocode and Code Tracing questions

Exams that ask this topic