From e280581719af9ac5078eabd5641569f058fd71e3 Mon Sep 17 00:00:00 2001 From: Hiro Funatsuka Date: Wed, 29 Apr 2026 16:26:25 +0900 Subject: [PATCH] Solve best time to buy and sell stock --- .../problem.md | 1 + 121_best_time_to_buy_and_sell_stock/step1.md | 26 +++++++++++++++++++ 121_best_time_to_buy_and_sell_stock/step2.md | 20 ++++++++++++++ 121_best_time_to_buy_and_sell_stock/step3.md | 20 ++++++++++++++ 4 files changed, 67 insertions(+) create mode 100644 121_best_time_to_buy_and_sell_stock/problem.md create mode 100644 121_best_time_to_buy_and_sell_stock/step1.md create mode 100644 121_best_time_to_buy_and_sell_stock/step2.md create mode 100644 121_best_time_to_buy_and_sell_stock/step3.md diff --git a/121_best_time_to_buy_and_sell_stock/problem.md b/121_best_time_to_buy_and_sell_stock/problem.md new file mode 100644 index 0000000..18c959d --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/problem.md @@ -0,0 +1 @@ +## 問題: [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/) diff --git a/121_best_time_to_buy_and_sell_stock/step1.md b/121_best_time_to_buy_and_sell_stock/step1.md new file mode 100644 index 0000000..7d89f51 --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/step1.md @@ -0,0 +1,26 @@ +# Step 1 + +- 変数を以下の通りにする + - stockを買う日: `buy_day` + - その日の値段: `price[buy_day]` + - 最大利益: `max_profit` +- forループを回していく中で、`price[i]`が`price[buy_day]`より安い場合は`price[buy_day]`を`price[i]`に更新する。高い場合は`max_profit`を更新する + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + buy_day = 0 + + for i, price in enumerate(prices): + if price < prices[buy_day]: + buy_day = i + else: + max_profit = max(max_profit, price - prices[buy_day]) + + return max_profit +``` + +時間計算量: O(n) + +空間計算量: O(1) diff --git a/121_best_time_to_buy_and_sell_stock/step2.md b/121_best_time_to_buy_and_sell_stock/step2.md new file mode 100644 index 0000000..c152f0d --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/step2.md @@ -0,0 +1,20 @@ +# Step 2 + +- ループ中にインデックスを気にせずとも書けた + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + buying_price = prices[0] + + for price in prices: + buying_price = min(buying_price, price) + max_profit = max(max_profit, price - buying_price) + + return max_profit +``` + +時間計算量: O(n) + +空間計算量: O(1) diff --git a/121_best_time_to_buy_and_sell_stock/step3.md b/121_best_time_to_buy_and_sell_stock/step3.md new file mode 100644 index 0000000..aa264fd --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/step3.md @@ -0,0 +1,20 @@ +# Step 3 + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + buying_price = prices[0] + + for price in prices: + buying_price = min(buying_price, price) + max_profit = max(max_profit, price - buying_price) + + return max_profit +``` + +1回目: 1分 9秒 + +2回目: 1分 10秒 + +3回目: 1分 11秒