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⁴
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Dynamic Programming
- Maximum SubarrayAI round · Medium
- Climbing StairsAI round · Easy
- Longest Increasing SubsequenceAI round · Medium
- Coin ChangeAI round · Medium
- House RobberMedium