CodeStride
Arrays

Best Time to Buy and Sell Stock

EasyInterview favoriteFree

You get a list prices, where prices[i] is the price of a stock on day i. You can buy one share on one day and sell it on a later day.

Return the most profit you can make from that one trade. If no trade makes money, return 0.

Example 1

Input
prices = [7, 1, 5, 3, 6, 4]
Output
5

Buy on day 1 at a price of 1, and sell on day 4 at a price of 6.

Example 2

Input
prices = [7, 6, 4, 3, 1]
Output
0

The price only falls, so the best choice is not to trade at all.

Example 3

Input
prices = [2, 4, 1]
Output
2

The lowest price comes last, with no day left to sell, so buying at 2 and selling at 4 is best.

Constraints

  • 1 <= length of prices <= 100,000
  • 0 <= prices[i] <= 10,000

Solve it in your browser

Write your solution in Python or JavaScript, run it on the examples, then submit it against hidden tests. 3 hints and worked solutions are there when you need them.