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
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 121. Best Time to Buy and Sell Stock
## STEP1
- 何も見ずに解いてみる
- これまでの最小値と現在の価格の差の最大値を求めればよい。
```python
import math


class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_prices_so_far = math.inf
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

_so_farは個人的にはつけないです。やや冗長に感じました。
また、max_profitも変数の意味合いとしては同じに感じますが、min_priceのみの理由が気になりました。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。_so_far の有無を厳密に使い分けておりませんでした。max_profit は最後に確定した値にフォーカスしていたので _so_far をつけなかった程度です。min_price についても確かに不要かもしれません。

以下のコメントも見つけました。
quinn-sasha/leetcode#24 (comment)

更新していく変数は多いですから明示する必要なければわざわざ言わないことの方が多い

max_profit = 0
for price in prices:
max_profit = max(max_profit, price - min_prices_so_far)
min_prices_so_far = min(min_prices_so_far, price)
return max_profit
```
#### memo
時間計算量: $O(n)$
空間計算量: $O(1)$

## STEP2
### プルリクやドキュメントを参照
- https://discord.com/channels/1084280443945353267/1206101582861697046/1219181674038820945
> prices が空の場合
- 0 となる。微妙な気はするが利益を出せない時は 0 という設計の関数なのでOKということにした。
- min_prices_so_far = math.inf とするか prices[0] とするか。0番目を特別扱いしない方が好み。
- https://github.com/olsen-blue/Arai60/pull/37/files
- 配列でそれぞれの日に得られる最大利益を記録。それほどわかりやすくならないかなと思った。
- House Robber の場合、前の家とその前の家の情報を使うため index で情報を取り出すことで漸化式のように理解でき見通しが良くなる。今回の問題では、max_profit[i] = prices[i] - min(prices[:i]) であり、min の部分を変数で更新しつつ管理する都合で、あまりその利益を得られないから。
- https://github.com/hayashi-ay/leetcode/pull/52/files
- STEP1 と同じ解法。
## STEP3
### 3回ミスなく書く
```python
import math


class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price_so_far = math.inf
max_profit = 0
for price in prices:
max_profit = max(max_profit, price - min_price_so_far)
min_price_so_far = min(min_price_so_far, price)
return max_profit
```

1分で1回Accept (STEP1と同じため省略)