From 9366d63f8039a87a2691934b636a7d70a4334add Mon Sep 17 00:00:00 2001 From: tokuhirat <54652919+tokuhirat@users.noreply.github.com> Date: Thu, 26 Jun 2025 07:31:25 +0900 Subject: [PATCH] Create 121. Best Time to Buy and Sell Stock.md --- .../121. Best Time to Buy and Sell Stock.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.md diff --git a/121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.md b/121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.md new file mode 100644 index 0000000..8b540ab --- /dev/null +++ b/121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.md @@ -0,0 +1,49 @@ +# 121. Best Time to Buy and Sell Stock +## STEP1 +- 何も見ずに解いてみる +- これまでの最小値と現在の価格の差の最大値を求めればよい。 +```python +import math + + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + min_prices_so_far = math.inf + max_profit = 0 + for price in prices: + max_profit = max(max_profit, price - min_prices_so_far) + min_prices_so_far = min(min_prices_so_far, price) + return max_profit +``` +#### memo +時間計算量: $O(n)$ +空間計算量: $O(1)$ + +## STEP2 +### プルリクやドキュメントを参照 +- https://discord.com/channels/1084280443945353267/1206101582861697046/1219181674038820945 + > prices が空の場合 + - 0 となる。微妙な気はするが利益を出せない時は 0 という設計の関数なのでOKということにした。 +- min_prices_so_far = math.inf とするか prices[0] とするか。0番目を特別扱いしない方が好み。 +- https://github.com/olsen-blue/Arai60/pull/37/files + - 配列でそれぞれの日に得られる最大利益を記録。それほどわかりやすくならないかなと思った。 + - House Robber の場合、前の家とその前の家の情報を使うため index で情報を取り出すことで漸化式のように理解でき見通しが良くなる。今回の問題では、max_profit[i] = prices[i] - min(prices[:i]) であり、min の部分を変数で更新しつつ管理する都合で、あまりその利益を得られないから。 +- https://github.com/hayashi-ay/leetcode/pull/52/files + - STEP1 と同じ解法。 +## STEP3 +### 3回ミスなく書く +```python +import math + + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + min_price_so_far = math.inf + max_profit = 0 + for price in prices: + max_profit = max(max_profit, price - min_price_so_far) + min_price_so_far = min(min_price_so_far, price) + return max_profit +``` + +1分で1回Accept (STEP1と同じため省略)