-
Notifications
You must be signed in to change notification settings - Fork 0
121. Best Time to Buy and Sell Stock #39
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
base: main
Are you sure you want to change the base?
Conversation
hayashi-ay
left a comment
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.
良いと思います
|
@hayashi-ay |
| min_price = min(min_price, price) | ||
| max_profit = max(max_profit, price - min_price) |
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.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
同日に買って売れないので、この2行入れ替えた方が正確だと思います。
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.
これは気づいていませんでした。
この更新したmin_priceは本来使えない価格なわけですね。
尚、更新された場合はmin_price = priceとなるので、max_profit = max(max_profit, 0)となり問題が起きなかったわけですね。
| def maxProfit(self, prices: List[int]) -> int: | ||
| min_price = prices[0] | ||
| max_profit = 0 | ||
| for price in prices: |
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.
すでにインデックス0の値は見ているので、インデックス1から始めた方が正確だと思います。
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.
有難うございます。
インデックスでループを回すよりシンプルで、prices[1:]とスライスを作るよりはいいかなということでこういう実装になったのですが、やってることが素直でなくなってしまいました。。
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.
math.inf を入れておくのは一つです。型が違うものが入ることになるので好まない人もいるでしょうが。
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://docs.python.org/ja/3/library/sys.html#sys.maxsize
ここら辺も選択肢にありましたが、これはこれで素直ではない気がしまして。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/