diff --git a/greedy_methods/best_time_to_buy_and_sell_stock.py b/greedy_methods/best_time_to_buy_and_sell_stock.py index 4aea19172ece..77fb5476b81a 100644 --- a/greedy_methods/best_time_to_buy_and_sell_stock.py +++ b/greedy_methods/best_time_to_buy_and_sell_stock.py @@ -26,17 +26,18 @@ def max_profit(prices: list[int]) -> int: return 0 min_price = prices[0] - max_profit: int = 0 + max_profit_value = 0 - for price in prices: - min_price = min(price, min_price) - max_profit = max(price - min_price, max_profit) + for price in prices[1:]: # start from second element + if price < min_price: + min_price = price + else: + max_profit_value = max(max_profit_value, price - min_price) - return max_profit + return max_profit_value if __name__ == "__main__": import doctest - doctest.testmod() print(max_profit([7, 1, 5, 3, 6, 4]))