-
Notifications
You must be signed in to change notification settings - Fork 0
121. Best Time to Buy and Sell Stock #18
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
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| cheapest_price = float("inf") | ||
| profit = 0 |
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.
max_profit などのほうが実態を表していてよいのではと思います。
| if price < cheapest_price: | ||
| cheapest_price = price | ||
| elif price > cheapest_price: | ||
| profit = max(profit, price - cheapest_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.
好みの範囲ですが、cheapest_price = min(cheapest_price, price) と書くほうが、それまでの最小の price を保持している感じがしてよいなあという気がします。
cheapest_price = min(cheapest_price, price)
profit = max(profit, price - chapest_price)などで分岐をなくせますね。
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| if prices is None: | ||
| return 0 |
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.
入力の検証があっても良いですが、リストであることを前提として以下のような方が適切かなと思いました。
if not prices:
raise ValueError("prices should not be empty") # or return 0| if profit < price - cheapest_price: | ||
| profit = price - cheapest_price | ||
|
|
||
| return profit |
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.
コードを見て思った感想を書きます。
手作業で行う処理を記載されているコードと思います。完全に手作業を再現するなら、price == cheapest_price の場合は continue と書きたい気もします(実際には書きませんが)。
一方で意味的に少し変形し、price < cheapest_price (もしくは逆)に等号を入れても成立するのでprice <= cheapest_price, price > cheapest_price (else) と分岐するようにしても良いかもしれません。
そこから形式的に変形していき、continue を使ってインデントを下げてみたり、下でコメントがあるようにmin, max を使ってみる、などコードを変形整理していくと良いかな思いました。
| for price in prices: | ||
| if price < cheapest_price: | ||
| cheapest_price = price | ||
| elif price > cheapest_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.
これ、else でもいいですか?
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.
はい。else: でもOKです。
121. Best Time to Buy and Sell Stock
次回予告: 206. Reverse Linked List