ProgrammingModerateInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
def profit(p):
    lo, best = float('inf'), 0
    for x in p:
        lo = min(lo, x)
        best = max(best, x - lo)
    return best
print(profit([7, 1, 5, 3, 6, 4]), profit([7, 6, 4, 3, 1]))
  1. A. 4 0
  2. B. 5 1
  3. C. 0 5
  4. D. 5 0

Correct answer: D. 5 0

The code buys at the running minimum and sells at the current price. Buying at 1 and selling at 6 gives 5, while a falling sequence has no profitable trade and gives 0.

More Python Programming questions

Exams that ask this topic