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- A. 6
- B. 17
- C. 8
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Currency notes are paid out greedily from the largest denomination down, using as many notes of each denomination as possible. For amount…
- A number is given as the digit string 1432219. Exactly 3 digits must be deleted (the digits keep their order) so that the remaining number…
- The same stack method is applied to the string 5317 with exactly 2 digits deleted, but now the aim is the LARGEST number. The procedure…
- Children have greed values 7, 8, 9, 10 and cookies have sizes 5, 6, 7, 8, 8. A child is content if the cookie given is at least his greed…
- Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval…
- Job durations (burst times) are 6, 8, 7, 3, 4 with all jobs arriving at time 0. Shortest-job-first runs them one after another in…