Skip to content

121. Best Time to Buy and Sell Stock - #32

Open
akmhmgc wants to merge 1 commit into
mainfrom
121
Open

121. Best Time to Buy and Sell Stock#32
akmhmgc wants to merge 1 commit into
mainfrom
121

Conversation

@akmhmgc

@akmhmgc akmhmgc commented Sep 25, 2025

Copy link
Copy Markdown
Owner

解いた問題

121. Best Time to Buy and Sell Stock

使用言語

Ruby

次に解く問題

122. Best Time to Buy and Sell Stock II

@akmhmgc akmhmgc added the ruby label Sep 25, 2025
Comment thread 121/step3.md
# @return {Integer}
def max_profit(prices)
prices_size = prices.size
return 0 if prices_size <= 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

試せていないので間違っていたら申し訳ないのですが、この行はなくても良い気がしました。
.each doの部分が回らずにそのまま0が出力されるのではないでしょうか。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます!
おっしゃる通りなくても良いのですがサイズが1以下の時の処理をわかりやすくするために残していました。

Comment thread 121/step3.md
end
max_profit
end
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます!
確かにそっちの方が意味がわかりやすいです。
どんな時でもmax_profitの更新をする必要はありませんね。

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.

3 participants