Best Time to Buy and Sell Stock
You get a list called prices. The value at position i is the price of one share on day i.
Pick one day to buy and a later day to sell. Return the largest profit you can make. If every possible trade loses money, return 0.
Examples
Input prices = [7, 1, 5, 3, 6, 4]
Output 5
Buy at 1 on day 1, sell at 6 on day 4.
Input prices = [7, 6, 4, 3, 1]
Output 0
Prices only fall, so no trade makes money.
Input prices = [2, 4, 1]
Output 2
Buy at 2, sell at 4. The drop to 1 comes too late to use.
Constraints
- 1 <= prices.length <= 100,000
- 0 <= prices[i] <= 10,000
Stuck? Take one hint at a time
Common mistakes
- Using the highest price minus the lowest price, which can sell before buying.
- Updating the lowest price after computing the profit, instead of before, on the same day.
- Returning a negative number instead of 0 when prices only fall.
- Starting the best profit at a very negative number.
Questions an interviewer may ask next
- You may buy and sell as many times as you like, but hold at most one share. What changes?
- Allow at most two transactions in total.
- Return the buy day and the sell day as well as the profit.
- Add a fee for each transaction.
How often this is reported
Commonly reported across 17 of 25 tracked companies
17/25
Grade B: Reported in more than one source. This reflects what candidates report, not a guarantee of what any company will ask.
prices
[7,1,5,3,6,4]
Expected output
5
Run checks these cases. Submit also runs hidden cases, and shows you the first one that fails.