From 24a6c67f9070c3240be77c81805ba527e5aae309 Mon Sep 17 00:00:00 2001 From: freemjstudio Date: Fri, 24 Jul 2026 20:34:54 +0900 Subject: [PATCH] add: best time to buy and sell stock --- .../freemjstudio.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/freemjstudio.py diff --git a/best-time-to-buy-and-sell-stock/freemjstudio.py b/best-time-to-buy-and-sell-stock/freemjstudio.py new file mode 100644 index 0000000000..42eeff4a39 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/freemjstudio.py @@ -0,0 +1,21 @@ +# first attempt - time out + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + for i in range(len(prices)): + profit = max(prices[i:]) - prices[i] + max_profit = max(max_profit, profit) + return max_profit + +# second attempt - greedy approach +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + min_price = prices[0] + + for i in range(len(prices)): + min_price = min(min_price, prices[i]) + profit = prices[i] - min_price + max_profit = max(max_profit, profit) + return max_profit