-
Notifications
You must be signed in to change notification settings - Fork 0
121. Best Time to Buy and Sell Stock #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tsadamor
wants to merge
1
commit into
main
Choose a base branch
from
0121-best-time-to-buy-and-sell-stock
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| # 121. Best Time to Buy and Sell Stock | ||
|
|
||
| - `prices`というint配列が与えられ、`prices[i]`はi番目の日における株価である。 | ||
| - 得られる最大の利益を返せ。必ず赤字になる場合は0を返せ。 | ||
| - 入力: | ||
| - 1 <= prices.length <= 10^5 | ||
| - 0 <= prices[i] <= 10^4 | ||
|
|
||
|
|
||
| ## Step1 | ||
| - 愚直に二重ループで購入と売却のすべての組み合わせを試せば、O(n^2) = 10^10ステップとなり、現実的なソリューションでない。 | ||
| - 配列を一回舐めるだけにすればO(n)になる。そのために必要な(とっておくべき)情報は、 | ||
| - 現時点での利益。これがないと今売るべきかの判断基準がない。 | ||
| - 現時点での購入金額。それより安いものにあたったら、(現時点での利益は変えないまま)買い替え候補をアップデートすべき。 | ||
|
|
||
| ```py | ||
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| profit = 0 | ||
| current_buy = prices[0] | ||
|
|
||
| for price in prices[1:]: | ||
| if price < current_buy: | ||
| current_buy = price | ||
| elif price - current_buy > profit: | ||
| profit = price - current_buy | ||
|
|
||
| return profit | ||
| ``` | ||
| - 線形探索になったので、時間計算量は`O(n)`、空間計算量は入力量にかかわらず`profit`と`current_buy`だけなのでO(1)。 | ||
|
|
||
|
|
||
| ## Step2 | ||
| ### AI | ||
| - `current_buy`は`min_price`のほうがよいのでは | ||
| - `profit`は`max_profit`のほうがよいのでは | ||
|
|
||
| ### [秒での判断](https://github.com/rimokem/arai60/pull/37/changes#diff-08b43bf1aed8bb6b426efa399de6161b7e4ce5815cfae7387f1b32d8b3c88712) | ||
| - `if`での比較に対し`min`, `max`を呼ぶ方法は関数呼び出しのオーバーヘッドがあるが、今回の問題設定などを考えると絶対視するほどのものではない、という議論。面白かった。 | ||
| - 自分自身はそもそも`min`, `max`での実装方法を考えてもいなかったので、書いてみる。 | ||
| ```py | ||
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| max_profit = 0 | ||
| min_price = prices[0] | ||
|
|
||
| for price in prices[1:]: | ||
| min_price = min(min_price, price) | ||
| max_profit = max(max_profit, price - min_price) | ||
|
|
||
| return max_profit | ||
| ``` | ||
| - リンク先のコードは`min_price`を`float("inf")`で初期化していた。ダイクストラっぽくて面白いと思ったが、Step1で選んだ、最初の株を買うという意味で`prices[0]`を継続した。 | ||
|
|
||
| ### [`prices`の長さが0のとき](https://github.com/h-masder/Arai60/pull/40/changes#diff-f87426cc46e157af84f5177a8fd56c038a8cdeb24e723aa0aafaa096c23eec77R42-R49) | ||
| - たしかに今のコードでは`IndexError`になる。 | ||
| - 問題の制約は`1 <= prices.length`なので0ではないことが保証されている。が、それを把握してエラーハンドリングを削ったわけでもない。エッジケースの想定が足りない。 | ||
| - エラーを`raise`するより、`if len(prices) == 0: return 0`を追加すればいいだろう。 | ||
| - それはそれとして、リンク先のコードはまったくべつの解法で驚いた。subarrayなるものは知らなかったので勉強になったが、計算量は現行のものと等しく、可読性は現行のもののほうが高いと感じられた。 | ||
|
|
||
| ### [後ろから見る](https://github.com/kazuki-official/leetcode/pull/37/changes) | ||
| - i日目以降の最大値を先に埋めておく方法。 | ||
| - 前から見るやり方はストリートアルゴリズム(全データが揃っていなくても処理可能、入力を保存する必要がない)、後ろから見るやり方はバッチ型(全データを手元に置く、追加空間が必要) | ||
|
|
||
| ### ブラッシュアップ | ||
| ```py | ||
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| if len(prices) == 0: | ||
| return 0 | ||
| max_profit = 0 | ||
| min_price = prices[0] | ||
|
|
||
| for price in prices[1:]: | ||
| if price < min_price: | ||
| min_price = price | ||
| elif price - min_price > max_profit: | ||
| max_profit = price - min_price | ||
|
|
||
| return max_profit | ||
| ``` | ||
|
|
||
| ## Step3 | ||
| 上記コードを三回再現。 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 全体的に読みやすかったです。 |
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
実行時間を見積もるといいと思います。
https://nuc.hatenadiary.org/entry/2025/11/29/#%E7%A7%92%E3%81%A7%E3%81%AE%E5%88%A4%E6%96%AD
Yuto729/leetcode#16 (comment)