ProgrammingHardAmazon OA · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[3] = {-3, -1, -4}
Integer cur = 0, best = 0
for (each i from 0 to 2)
    cur = cur + a[i]
    if (cur < 0)
        cur = 0
    end if
    if (cur > best)
        best = cur
    end if
end for
Print best
  1. A. -1
  2. B. 0
  3. C. -3
  4. D. -8

Correct answer: B. 0

best starts at 0 and cur is reset to 0 whenever it goes negative, so with all-negative data nothing ever beats 0. This is the known flaw of this form of Kadane's algorithm; the true largest subarray sum is −1.

More Pseudocode and Code Tracing questions

Exams that ask this topic