Best Time to Buy and Sell Stock
Easy Dynamic Programming
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⁴
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
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.
See the AI roundWatch the explanation
More Dynamic Programming
- Maximum SubarrayAI round · Medium
- Climbing StairsAI round · Easy
- Longest Increasing SubsequenceAI round · Medium
- Coin ChangeAI round · Medium
- Unique PathsAI round · Medium