Skip to content

Conversation

@skypenguins
Copy link
Owner

121. Best Time to Buy and Sell Stock

次回予告: 206. Reverse Linked List

@skypenguins skypenguins self-assigned this Aug 5, 2025
class Solution:
def maxProfit(self, prices: List[int]) -> int:
cheapest_price = float("inf")
profit = 0

Choose a reason for hiding this comment

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

max_profit などのほうが実態を表していてよいのではと思います。

Comment on lines +86 to +89
if price < cheapest_price:
cheapest_price = price
elif price > cheapest_price:
profit = max(profit, price - cheapest_price)

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

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

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:
Copy link

Choose a reason for hiding this comment

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

これ、else でもいいですか?

Copy link
Owner Author

Choose a reason for hiding this comment

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

はい。else: でもOKです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants