ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer p[6] = {7, 1, 5, 3, 6, 4}
Integer lo = p[0], one = 0, many = 0
for (each i from 1 to 5)
    lo = min(lo, p[i])
    one = max(one, p[i] - lo)
    if (p[i] > p[i - 1])
        many = many + p[i] - p[i - 1]
    end if
end for
Print one, many
  1. A. 6 7
  2. B. 5 7
  3. C. 5 5
  4. D. 4 7

Correct answer: B. 5 7

one is the best single buy-then-sell profit: buy at 1, sell at 6, profit 5. many adds every day-to-day rise, which is the best profit with unlimited trades: (5 − 1) + (6 − 3) = 7. Output 5 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic