50 XP

64. Best time to buy and sell

Intermediate greedy lists

You are given a share's price on each of a number of days, in order. You may buy one share on one day and sell it on a later day.

Write a function max_profit(prices) that takes the list of prices and returns the largest profit you could make: the selling price minus the buying price.

  • You must buy before you sell: the sale is on a later day than the purchase.
  • If no sale would make money (the prices only fall or stay the same), don't trade: the answer is 0.
  • With fewer than two days there is nothing to trade, so the answer is 0.

The highest price minus the lowest isn't always possible: the lowest price may come after the highest.

Example 1

Inputprices = [9, 2, 6, 1, 4, 8]
Output7
ExplanationBuy at 1 on day 4, sell at 8 on day 6.

Example 2

Inputprices = [3, 9, 1, 5]
Output6
ExplanationBuy at 3, sell at 9. Buying at 1 makes 4.

Example 3

Inputprices = [8, 6, 3]
Output0
ExplanationPrices only fall: better not to trade.

Constraints

  • prices has 0 to 500 whole numbers, each from 0 to 10,000.

Submit also runs 9 more tests you can't see.

Practises For Loops (lesson 13).

Code
def max_profit(prices):
    """Find the best profit from one buy and a later sale.

    prices: list of int, one price per day, in order
    Returns: int, the largest sell price minus buy price,
        or 0 if no trade makes money
    """
    # Write your code here
    pass