Skip to content

198. House Robber#35

Open
dxxsxsxkx wants to merge 1 commit into63_unique_paths_2from
198_house_robber
Open

198. House Robber#35
dxxsxsxkx wants to merge 1 commit into63_unique_paths_2from
198_house_robber

Conversation

@dxxsxsxkx
Copy link
Copy Markdown
Owner

for (int i = 2; i < nums.size(); ++i) {
max_returns[i] = std::max(max_returns[i - 2] + nums[i], max_returns[i - 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.

読みやすいと思います。

int current_max_return = std::max(nums[0], nums[1]);

int second_previous_max_return = nums[0];
int previous_max_return = current_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から書き始めた方が読みやすいかもしれないと思いました。
あと、second_previous, previousは0で初期化してしまってfor文をi=0からはじめても動く気がします。そうすると最初のearly returnも消せますかね。

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.

ありがとうございます!おっしゃる通りで、シンプルになりました。

#include <vector>
class Solution {
public:
    int rob(std::vector<int>& nums) {

        int current_max_return = 0;
        int previous_max_return = 0;
        int second_previous_max_return = 0;

        for (int i = 0; i < nums.size(); ++i) {
            current_max_return = std::max(previous_max_return, second_previous_max_return + nums[i]);
            
            second_previous_max_return = previous_max_return;
            previous_max_return = current_max_return;
        }

        return current_max_return;
    }
};

previous_max_return = current_max_return;
}

return current_max_return;
Copy link
Copy Markdown

@potrue potrue Feb 21, 2026

Choose a reason for hiding this comment

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

この変数(current_max_return)は保存しておく必要はない気がします(for文の中身を除いて常にprevious_max_returnと同一になるので。)
好みかもしれませんが、for文の中でのみ一時的な変数を定義して、最後のreturnはprevious_max_returnを返してしまっていいと思います。

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.

ありがとうございます。確かにそうなのですが、temp があるよりも意味のある名前がついた current_max_return がある方がわかりやすいかなと思いました。

return nums[0];
}

// Maximum amount of money that can be robbed if you rob each house
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

if you rob each house

ここの意味が取れませんでした。文字通り読むと(隣り合わせの制約を無視して)すべての家から盗む、ということかなと思ったのですが、それだと用途と異なるようにも思えて…。

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.

3 participants