64. Best time to buy and sell
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
prices = [9, 2, 6, 1, 4, 8]7Example 2
prices = [3, 9, 1, 5]6Example 3
prices = [8, 6, 3]0Constraints
priceshas 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).
- If you sell on a given day, the best day to have bought is the cheapest day before it.
- So walk through the days once, keeping the lowest price seen so far. Each day,
price - lowestis the best profit from selling that day. - Keep the largest of those profits, starting from 0, which covers falling prices and short lists. Checking every pair of days works too, but takes far more steps.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.