Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions Python3/121. Best Time to Buy and Sell Stock.md
Original file line number Diff line number Diff line change
@@ -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
Comment on lines +49 to +50
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この分岐は無くても正しく動くため、自分だったら書かないかなと思いました。

min_buy = prices[0]
max_profit = 0
for i in range(1, len(prices)):
if prices[i] < min_buy:
min_buy = prices[i]
continue

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この continue は違う日に売り買いするように書いていると理解しました。これは、max_profit を先に処理することでも可能と思いました。趣味の範囲と思います。

max_profit = max(max_profit, prices[i] - min_buy)
return max_profit
```