Skip to content

213. House Robber II#34

Open
5103246 wants to merge 1 commit intomainfrom
213-house-robber-ii
Open

213. House Robber II#34
5103246 wants to merge 1 commit intomainfrom
213-house-robber-ii

Conversation

@5103246
Copy link
Copy Markdown
Owner

@5103246 5103246 commented Nov 21, 2025

}

private:
int CaluculateMaxMoney(const vector<int>& houses, int left, int right) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

このメソッド名ですが、robメソッドも最大金額を計算する点では共通していてrobとの違いが分かりにくいと感じるので、自分ならrob_sectionやrob_rangeとかにすると思います。

Comment on lines +86 to +90
for (int i = left; i < right; ++i) {
int total_money = houses[i] + max_money_without_last;
max_money_without_last = max(max_money_without_last, max_money_with_last);
max_money_with_last = total_money;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここは一時変数を置く方法のほか、同時更新する方法もありますね。

private:
    int CaluculateMaxMoney(const vector<int>& houses, int start, int end) {
        int max_money_with_last = 0;
        int max_money_without_last = 0;

        for (int i = start; i < end; ++i) {
            UpdateMoney(max_money_without_last, max_money_with_last, houses[i]);
        }
        
        return max(max_money_with_last, max_money_without_last);
    }

    void UpdateMoney(int& max_money_without_last, int& max_money_with_last, int val) {
        tie(max_money_without_last, max_money_with_last) = make_pair(
            max(max_money_without_last, max_money_with_last),
            max_money_without_last + val
        );
    }
};

更新ロジックを試しに切り出してみたんですが、あんまり良くないかもしれません...

Comment on lines +127 to +134
int max_money_with_last = 0;
int max_money_without_last = 0;
for (int i = start; i < end; ++i) {
int current_total = houses[i] + max_money_without_last;
max_money_without_last = max(max_money_without_last, max_money_with_last);
max_money_with_last = current_total;
}
return max(max_money_with_last, max_money_without_last);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

細かいですが、max_money_without_last, max_money_with_lastの初期化とreturnでmax()の引数に渡す順番は、更新順序と合わせた方が自然な気がします。

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.

2 participants