📘
Best Time to Buy and Sell Stock
EasySliding Window
Given an array prices where prices[i] is the price of a given stock on the i-th day, find the maximum profit you can achieve by buying on one day and selling on a later day.
If no profit is possible, return 0.
Example:
Input:
7,1,5,3,6,4
Output:
5
Reasoning:
- We start by initializing the minimum price and maximum profit: min_price=7, max_profit=0.
- We then iterate through the array, updating min_price and max_profit as we find lower prices and higher profits:
- On the second day, min_price=1.
- On the third day, max_profit=5−1=4.
- On the fifth day, max_profit=6−1=5.
- The final output is max_profit=5.
Constraints:
- 1 <= len(prices) <= 10^5
- 0 <= prices[i] <= 10^4
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.