From e517365e8f9b129402955a66f3165cdf7b04b2de Mon Sep 17 00:00:00 2001 From: Hiro Funatsuka Date: Tue, 5 May 2026 14:54:03 +0900 Subject: [PATCH] Solve best time to buy and sell stock ii --- .../problem.md | 1 + .../step1.md | 19 +++++++++++++++++++ .../step2.md | 16 ++++++++++++++++ .../step3.md | 17 +++++++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 122_best_time_to_buy_and_sell_stock_ii/problem.md create mode 100644 122_best_time_to_buy_and_sell_stock_ii/step1.md create mode 100644 122_best_time_to_buy_and_sell_stock_ii/step2.md create mode 100644 122_best_time_to_buy_and_sell_stock_ii/step3.md diff --git a/122_best_time_to_buy_and_sell_stock_ii/problem.md b/122_best_time_to_buy_and_sell_stock_ii/problem.md new file mode 100644 index 0000000..6a7dc66 --- /dev/null +++ b/122_best_time_to_buy_and_sell_stock_ii/problem.md @@ -0,0 +1 @@ +## 問題: [122. Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) diff --git a/122_best_time_to_buy_and_sell_stock_ii/step1.md b/122_best_time_to_buy_and_sell_stock_ii/step1.md new file mode 100644 index 0000000..048f72d --- /dev/null +++ b/122_best_time_to_buy_and_sell_stock_ii/step1.md @@ -0,0 +1,19 @@ +# Step 1 + +- 各整数を折れ線グラフの点と考え、右上がりになるものを合計に加えていく +- 上記を実現する式: $maxProfit=maxProfit + max(prices[i] - prices[i-1], 0)$ + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if len(prices) <= 1: + return 0 + max_profit = 0 + for i in range(1, len(prices)): + max_profit += max(prices[i] - prices[i - 1], 0) + return max_profit +``` + +時間計算量: $O(n)$ + +空間計算量: $O(1)$ diff --git a/122_best_time_to_buy_and_sell_stock_ii/step2.md b/122_best_time_to_buy_and_sell_stock_ii/step2.md new file mode 100644 index 0000000..4fae21c --- /dev/null +++ b/122_best_time_to_buy_and_sell_stock_ii/step2.md @@ -0,0 +1,16 @@ +# Step 2 + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if len(prices) < 2: + return 0 + max_profit = 0 + for i in range(1, len(prices)): + max_profit += max(prices[i] - prices[i - 1], 0) + return max_profit +``` + +時間計算量: $O(n)$ + +空間計算量: $O(1)$ diff --git a/122_best_time_to_buy_and_sell_stock_ii/step3.md b/122_best_time_to_buy_and_sell_stock_ii/step3.md new file mode 100644 index 0000000..00180d0 --- /dev/null +++ b/122_best_time_to_buy_and_sell_stock_ii/step3.md @@ -0,0 +1,17 @@ +# Step 3 + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if len(prices) < 2: + return 0 + max_profit = 0 + for i in range(1, len(prices)): + max_profit += max(prices[i] - prices[i - 1], 0) + return max_profit +``` +1回目: 0分 56秒 + +2回目: 0分 48秒 + +3回目: 0 53秒