From 5bd821965c2960f0070d1104fc5b8245368c9ca5 Mon Sep 17 00:00:00 2001 From: Alex Khaerov Date: Wed, 29 Jun 2022 00:43:36 +0800 Subject: [PATCH] Update 121-Best-Time-To-Buy-and-Sell-Stock.py --- 121-Best-Time-To-Buy-and-Sell-Stock.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/121-Best-Time-To-Buy-and-Sell-Stock.py b/121-Best-Time-To-Buy-and-Sell-Stock.py index 43f25e419..815bcee59 100644 --- a/121-Best-Time-To-Buy-and-Sell-Stock.py +++ b/121-Best-Time-To-Buy-and-Sell-Stock.py @@ -1,10 +1,8 @@ class Solution: def maxProfit(self, prices: List[int]) -> int: - res = 0 - - l = 0 - for r in range(1, len(prices)): - if prices[r] < prices[l]: - l = r - res = max(res, prices[r] - prices[l]) - return res + max_profit = 0 + min_price = float("inf") + for price in prices: + min_price = min(price, min_price) + max_profit = max(price - min_price, max_profit) + return max_profit