ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[5] = {2, 3, -2, 4, -1}
Integer mx = a[0], mn = a[0], best = a[0], t
for (each i from 1 to 4)
    if (a[i] < 0)
        t = mx
        mx = mn
        mn = t
    end if
    mx = max(a[i], mx * a[i])
    mn = min(a[i], mn * a[i])
    best = max(best, mx)
end for
Print best
  1. A. 6
  2. B. 24
  3. C. 48
  4. D. 4

Correct answer: C. 48

This tracks the largest and smallest products ending at each index, swapping them at a negative number. The two negatives cancel, so the whole array is best: 2 × 3 × (−2) × 4 × (−1) = 48. Stopping at the first negative gives 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic