ProgrammingHardInfosys · Cognizant

Stock prices by day: 3, 8, 2, 9, 1, 6. One share may be bought once and sold once later (later day only). The procedure below runs. What is printed?

Stock prices by day: 3, 8, 2, 9, 1, 6. One share may be bought once and sold once later (later day only). The procedure below runs. What is printed?
mn = price[0]; best = 0
for each later day price x
    best = max(best, x - mn)
    mn = min(mn, x)
end for
Print best
  1. A. 6
  2. B. 17
  3. C. 8
  4. D. 7

Correct answer: D. 7

The best sale comes from buying at the lowest earlier price: buy at 2 and sell at 9 for 7. Buying at the first price, summing every rise (unlimited trades), or ignoring day order all give other values.

More Pseudocode and Code Tracing questions

Exams that ask this topic