Best Time to Buy and Sell Stock

Easy Dynamic Programming AI round

prices holds the price of one share on each day, in order.

You may buy on one day and sell on a later day, once, or make no trade at all.

Return the largest profit you can make, or 0 if no trade makes money.

Example 1

Input: prices = [12,7,15,9,20,11]
Output: 13

Buy on day 1 at 7 and sell on day 4 at 20, for 13. The 12 on day 0 costs more than the 7, so waiting for the dip pays better.

Example 2

Input: prices = [30,20,10]
Output: 0

Example 3

Input: prices = [10,4,4,10,1,6]
Output: 6

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Watch the explanation

More Dynamic Programming

All Dynamic Programming problems