Easy
Best Time to Buy and Sell Stock
- Time limit
- 1 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Greedy on Sequences
Description
Description
You are given an array prices where prices[i] is the price of a stock on day i. You may complete at most one transaction: buy on one day and sell on a later day. Return the maximum profit achievable. If no profit is possible (or the array has fewer than two prices), return 0.
Examples
Example 1
- Input:
prices = [7, 1, 5, 3, 6, 4] - Output:
5 - Explanation: Buy on day 2 (price
1), sell on day 5 (price6); profit6 - 1 = 5.
Example 2
- Input:
prices = [7, 6, 4, 3, 1] - Output:
0 - Explanation: Prices only fall, so no transaction is profitable.
Example 3
- Input:
prices = [1, 2] - Output:
1
Expected Function Behavior
Constraints
0 <= prices.length <= 1000000 <= prices[i] <= 1000000
Sample cases
3Sample 1
Input
prices = [7,1,5,3,6,4]
Expected output
5
Sample 2
Input
prices = [7,6,4,3,1]
Expected output
0
Skills and languages
Patterns
- Stock Trading DP Family
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer