ProgrammingVery hardAmazon OA · Goldman Sachs OA

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 h[12] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}
Integer lmax[12], rmax[12], w = 0
lmax[0] = h[0]
for (each i from 1 to 11)
    lmax[i] = max(lmax[i - 1], h[i])
end for
rmax[11] = h[11]
for (each i from 10 down to 0)
    rmax[i] = max(rmax[i + 1], h[i])
end for
for (each i from 0 to 11)
    w = w + min(lmax[i], rmax[i]) - h[i]
end for
Print w
  1. A. 5
  2. B. 8
  3. C. 6
  4. D. 10

Correct answer: C. 6

Water above bar i is min(tallest bar on its left, tallest on its right) − h[i]. Adding up: 1 (index 2) + 1 + 2 + 1 (indices 4–6) + 1 (index 9) = 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic