Skip to main content

Best Time to Buy and Sell Stock

EasyArraysGreedy323 tests

You are given an array prices where prices[i] is the price of a stock on day i.

You want to maximise your profit by choosing one day to buy and a different, later day to sell. Return the maximum profit you can make. If no profit is possible, return 0.

Example 1

text

Buy on day 1 (price 1) and sell on day 4 (price 6): profit 5. Note that buying on day 1 and selling on day 0 is not allowed.

Example 2

text

Prices only fall, so no transaction makes a profit.

Careful: the answer is not simply the maximum minus the minimum. The minimum has to come first.

Examples

Example 1

Input:
[7,1,5,3,6,4]
Output:
5

Buy at 1 on day 1, sell at 6 on day 4.

Example 2

Input:
[7,6,4,3,1]
Output:
0

Prices only fall, so the best move is not to trade.

Example 3

Input:
[2,4,1]
Output:
2

Buy at 2, sell at 4. The 1 comes too late to be useful.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Run checks your code against the 3 examples. Submit checks it against all 323 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.