Conversation
potrue
reviewed
Sep 26, 2025
| # @return {Integer} | ||
| def max_profit(prices) | ||
| prices_size = prices.size | ||
| return 0 if prices_size <= 1 |
There was a problem hiding this comment.
試せていないので間違っていたら申し訳ないのですが、この行はなくても良い気がしました。
.each doの部分が回らずにそのまま0が出力されるのではないでしょうか。
Owner
Author
There was a problem hiding this comment.
コメントありがとうございます!
おっしゃる通りなくても良いのですがサイズが1以下の時の処理をわかりやすくするために残していました。
| end | ||
| max_profit | ||
| end | ||
| ``` |
There was a problem hiding this comment.
price[i] が min_price より小さい場合は max_profit の更新はないため、min_price を更新して次のループに進むのもよさそうかなと思いました。
def max_profit(prices)
prices_size = prices.size
return 0 if prices_size <= 1
min_price = prices.first
max_profit = 0
(1...prices_size).each do |i|
if prices[i] < min_price
min_price = prices[i]
next
end
max_profit = [max_profit, prices[i] - min_price].max
end
max_profit
end
Owner
Author
There was a problem hiding this comment.
コメントありがとうございます!
確かにそっちの方が意味がわかりやすいです。
どんな時でもmax_profitの更新をする必要はありませんね。
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
使用言語
Ruby
次に解く問題
122. Best Time to Buy and Sell Stock II