Best time to buy and sell once
Standard · Write code · about 10 min
prices[i] is a stock's price on day i. Buy one share on one day and sell it on a later day.
Return the largest profit you can make, or 0 if no trade makes money.
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 do not trade.
Constraints
- 1 ≤ prices.length ≤ 10,000
- 0 ≤ prices[i] ≤ 10,000
Learn the idea first: Kadane's algorithm and maximum subarray, a visual lesson.
More Kadane's algorithm and maximum subarray problems
- Follow Kadane's two numbers Warm-up
- Maximum circular subarray Standard
- Maximum product subarray Challenge