Open
Conversation
ryosuketc
reviewed
Aug 6, 2025
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| cheapest_price = float("inf") | ||
| profit = 0 |
Comment on lines
+86
to
+89
| if price < cheapest_price: | ||
| cheapest_price = price | ||
| elif price > cheapest_price: | ||
| profit = max(profit, price - cheapest_price) |
There was a problem hiding this comment.
好みの範囲ですが、cheapest_price = min(cheapest_price, price) と書くほうが、それまでの最小の price を保持している感じがしてよいなあという気がします。
cheapest_price = min(cheapest_price, price)
profit = max(profit, price - chapest_price)などで分岐をなくせますね。
tokuhirat
reviewed
Aug 6, 2025
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| if prices is None: | ||
| return 0 |
There was a problem hiding this comment.
入力の検証があっても良いですが、リストであることを前提として以下のような方が適切かなと思いました。
if not prices:
raise ValueError("prices should not be empty") # or return 0
tokuhirat
reviewed
Aug 6, 2025
| if profit < price - cheapest_price: | ||
| profit = price - cheapest_price | ||
|
|
||
| return profit |
There was a problem hiding this comment.
コードを見て思った感想を書きます。
手作業で行う処理を記載されているコードと思います。完全に手作業を再現するなら、price == cheapest_price の場合は continue と書きたい気もします(実際には書きませんが)。
一方で意味的に少し変形し、price < cheapest_price (もしくは逆)に等号を入れても成立するのでprice <= cheapest_price, price > cheapest_price (else) と分岐するようにしても良いかもしれません。
そこから形式的に変形していき、continue を使ってインデントを下げてみたり、下でコメントがあるようにmin, max を使ってみる、などコードを変形整理していくと良いかな思いました。
oda
reviewed
Aug 6, 2025
| for price in prices: | ||
| if price < cheapest_price: | ||
| cheapest_price = price | ||
| elif price > cheapest_price: |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
121. Best Time to Buy and Sell Stock
次回予告: 206. Reverse Linked List