diff --git a/Python3/121. Best Time to Buy and Sell Stock.md b/Python3/121. Best Time to Buy and Sell Stock.md new file mode 100644 index 0000000..e1dfb6e --- /dev/null +++ b/Python3/121. Best Time to Buy and Sell Stock.md @@ -0,0 +1,59 @@ +## Step 1. Initial Solution + +- Easyなのでそんなに手間はかからないはず +- 最も単純に考えれば各priceについてリスト全体を調べればよいがそれは遅い +- 最小値と最大値を判別して、今までの最大の利益を超えたら更新で行けそう + - 最大値を保持していたがよく考えると必要ないので削除して以下 + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + min_price = prices[0] + max_profit = 0 + for price in prices: + if price < min_price: + min_price = price + max_profit = max(max_profit, price - min_price) + return max_profit +``` + +### Complexity Analysis + +- 時間計算量:O(n) +- 空間計算量:O(1) + +## Step 2. Alternatives + +- 空配列に対して + - エラーになる + - 0を使わずに初期値を決めれば空配列に対してもエラーを返さない + - https://github.com/tokuhirat/LeetCode/pull/37/files#diff-51a148e3b52594eafc6999c4517eed5eb2c8eb1eeaa6f0a711ef9fdca11d3122R24 + - 1日目に買って一日目に売れば0なのは分かるが取引をそもそもしていないのに0を返すのは変な気がした +- 逆方向に見ていくこともできる + - ちょっとだけ短いかもしれないが、あまり意味的には嬉しさがない + - https://github.com/fhiyo/leetcode/pull/38/files#r1667641801 +- あえてリストで保持するという考え方もある + - 個人的には全てのデータが公開されている中での分析というイメージなのでリストに保持する必要性はあまり感じない + - 各時点で判断するようなアルゴリズムだったらあっても良いかも + - https://github.com/olsen-blue/Arai60/pull/37/files#diff-0474f0ee7711182f0e97bb4047531dc4c65356748eafab139512400ac88c5c0bR96 + +## Step 3. Final Solution + +- 色々な書き方ができるが一旦これで + - len = 0 はエラー + - math.infは使わない + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if len(prices) == 1: + return 0 + min_buy = prices[0] + max_profit = 0 + for i in range(1, len(prices)): + if prices[i] < min_buy: + min_buy = prices[i] + continue + max_profit = max(max_profit, prices[i] - min_buy) + return max_profit +```