121. Best Time to Buy and Sell Stock
Array, DP ·Problem Statement
link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
You are given an array prices where prices[i] is the price of a given stock on the ith 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:
Input: prices = [7,1,5,3,6,4]
Output: 5
Input: prices = [7,6,4,3,1]
Output: 0
Solution Approach
The key to solving this problem lies in finding the minimum price to buy the stock and the corresponding maximum price difference to sell the stock.
Algorithm
- Initialize min_buy with the first price.
- Traverse through prices; if a lower price is found, update min_buy. Otherwise, calculate profit and update max_profit if it’s higher.
- Return max_profit at the end.
Implement
def maxProfit(self, prices: List[int]) -> int:
min_buy = prices[0]
max_profit = 0
for p in prices[1:]:
if p < min_buy:
min_buy = p
else:
max_profit = max(max_profit,p - min_buy)
return max_profit