121. Best Time to Buy and Sell Stock
easyArray · Dynamic Programming
read the problem on leetcode →
first solved 13 Aug 2024 · 2 accepted submissions
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit=0
# profit=buytoday-cheapestsofar
min_price=prices[0]
for price in prices:
min_price=min(price, min_price)
max_profit=max(max_profit,price - min_price)
return max_profit
class Solution(object):
def maxProfit(self, prices):
profit = 0
buy = prices[0]
for sell in prices[1:]:
if sell > buy:
profit = max(profit, sell - buy)
else:
buy = sell
return profit