Best Time To Buy And Sell Stock Problem
Description
LeetCode Problem 121.
You are given an array prices where prices[i] is the price of a given stock on the i^th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
Solution
Approach: One Pass, Tracking the Lowest Price
Checking every pair of buy and sell days takes O(n2) time. Instead, fix the sell day: if we sell on day i, the best day to have bought is the day with the lowest price before it. So we only need the minimum price seen so far.
Walk through the prices once, keeping two numbers:
lowest: the cheapest price up to now.best: the best profit found so far, starting at 0 (doing nothing is allowed).
For each price, first update best = max(best, price - lowest) (sell today), then lowest = min(lowest, price).
The order of these two lines does not change the result here: if today is the new lowest, selling on the same day gives a profit of 0, which never beats best. What matters is that the minimum only looks backwards. Taking the global minimum and maximum of the array would be wrong when the minimum comes after the maximum, as in [3, 8, 1, 4], where the answer is 5, not 3.
Complexity: O(n) time and O(1) space, where n is the length of prices.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
lowest = prices[0] # cheapest price so far: the best day to have bought
best = 0
for price in prices:
best = max(best, price - lowest) # profit if we sell today
lowest = min(lowest, price)
return best