-
Notifications
You must be signed in to change notification settings - Fork 0
198. House Robber #35
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
| int rob(std::vector<int>& nums) { | ||
| int prev_max = 0; | ||
| int current_max = 0; | ||
| for (const int num : nums) { |
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.
あまりわかっていないコメントで恐縮ですが、counst auto& を使うのもありでしょうか?
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.
autoはコンパイル時に型を自動で推論するものなので、コンパイル後のプログラムはconst auto&はconst int&と同じになるのではないかと認識しています。
&をつけると参照渡しになり、変数のコピーではなく変数のメモリアドレスが渡されるようなのですが、これをつけずに値渡しにしておくと、値のサイズが小さい場合にはCPUのレジスターに直接書き込まれ、メモリアドレスを介してアクセスする場合に比べて高速になる場合があるようです。intなどサイズが小さい値の場合は、アドレスを渡しても値のコピーを渡しても必要なサイズが同じあるいは値のコピーを渡すほうが小さく、上記のパフォーマンス高速化の観点から見て値渡し(&をつけずにconst intまたはconst autoとする)の方が良いとされているのだと思います。
(間違っていたらすみません)
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.
丁寧に教えていただきありがとうございます!
| int next_max = std::max(current_max, prev_max + num); | ||
| prev_max = current_max; | ||
| current_max = next_max; |
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.
これはこれでありかなと思いはしますが、今見ている num を基準に考えると、1 軒前まで、2 軒前まで、現在まで max を見ている、と考えたほうが (個人的には) 理解しやすいように思います。
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.
これ少し迷ったのですが、最後にprev_maxをリターンすることになるのがちょっと気に食わなくてこちらにしてしまいました。。
問題文:
https://leetcode.com/problems/house-robber/description/