Skip to content

213. House Robber 2#36

Open
dxxsxsxkx wants to merge 1 commit into198_house_robberfrom
213_house_robber_2
Open

213. House Robber 2#36
dxxsxsxkx wants to merge 1 commit into198_house_robberfrom
213_house_robber_2

Conversation

@dxxsxsxkx
Copy link
Copy Markdown
Owner

int rob(std::vector<int>& nums) {
int num_house = nums.size();

if (num_house == 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.

num_house <= 3 の場合に max_element するのも一つの選択肢だと思います

class Solution {
public:
int rob(std::vector<int>& nums) {
int num_houses = nums.size();
Copy link
Copy Markdown

@potrue potrue Feb 22, 2026

Choose a reason for hiding this comment

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

これぐらいだったら自分はnums.size()のまま使ってしまいそうです。


for (int i = start; i <= end; ++i) {
current_max_return = std::max(second_previous_max_return + nums[i], previous_max_return);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この改行は自分ならつけないですかね。L16-17にもついてないですし、重要なロジックの区切りがあるわけでもない気がします。

std::vector<std::vector<int>> max_returns(nums.size(), std::vector<int>(2, 0));

// Did not rob nums[0]
max_returns[0][0] = 0;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

一次元目と二次元目の添え字が何を表しているのか分かりづらく感じました。二次元目の添え字を定数とするのが良いでしょうか。

int second_previous_max_return = 0;

for (int i = start; i <= end; ++i) {
current_max_return = std::max(second_previous_max_return + nums[i], previous_max_return);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

それぞれの変数の命名がややこなれていない印象を受けました。特に second_previous_ など。例えば、previous を言い換えて以下はどうでしょうか。

  • max_return
  • max_return_robbed_last
  • max_return_skipped_last

int previous_max_return = 0;
int second_previous_max_return = 0;

for (int i = start; i <= end; ++i) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

個人的には、end はexclusiveであるのが自然に思います。inclusiveなら first, last がしっくりきます。

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.

ありがとうございます。
そういう使い分けの発想がなかったので参考になります。

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants