From b111143f461418ca0a61de6ee26d76f94c643f67 Mon Sep 17 00:00:00 2001 From: tokuhirat <54652919+tokuhirat@users.noreply.github.com> Date: Sun, 29 Jun 2025 10:11:41 +0900 Subject: [PATCH] Create 122. Best Time to Buy and Sell Stock II.md --- ...122. Best Time to Buy and Sell Stock II.md | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.md diff --git a/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.md b/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.md new file mode 100644 index 0000000..4434c60 --- /dev/null +++ b/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.md @@ -0,0 +1,62 @@ +# 122. Best Time to Buy and Sell Stock II +## STEP1 +- 何も見ずに解いてみる +- 前日より増加している分を足し合わせればよい。 +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + for i in range(len(prices) - 1): + if prices[i] < prices[i + 1]: + max_profit += prices[i + 1] - prices[i] + return max_profit +``` +#### memo +時間計算量: $O(n)$ +空間計算量: $O(1)$ + +## STEP2 +### プルリクやドキュメントを参照 +- https://github.com/hayashi-ay/leetcode/pull/56/files +- https://github.com/olsen-blue/Arai60/pull/38/files + - 株を持っている/いない場合の保有現金最大値を管理する方法 + - https://github.com/olsen-blue/Arai60/pull/38/files#r1980562479 + - これを読むまでは全然わからなかった。変数名大事ですね。 + - 遷移としては、株を持っている/持っていない、から売る/買う、そのままの4通りある。STEP1の書き方だと単純に利益が出る時に売買するのでシンプルな気がする。 +- ピークと谷を見つける書き方もある。毎日売り買いするよりも自然かもしれない。 +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + def find_next_highest(index: int) -> int: + while index < len(prices) - 1 and prices[index] <= prices[index + 1]: + index += 1 + return index + + def find_next_lowest(index: int) -> int: + while index < len(prices) - 1 and prices[index + 1] <= prices[index]: + index += 1 + return index + + max_profit = 0 + index = 0 + while index < len(prices): + valley_index = find_next_lowest(index) + peak_index = find_next_highest(valley_index) + max_profit += prices[peak_index] - prices[valley_index] + index = peak_index + 1 + return max_profit +``` + +## STEP3 +### 3回ミスなく書く +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + for i in range(len(prices) - 1): + if prices[i] < prices[i + 1]: + max_profit += prices[i + 1] - prices[i] + return max_profit +``` + +2分で1回Accept (STEP1と同じため省略)