[LeetCode] House Robber V

3840. House Robber V

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed and is protected by a security system with a color code.

You are given two integer arrays nums and colors, both of length n, where nums[i] is the amount of money in the i^th house and colors[i] is the color code of that house.

You cannot rob two adjacent houses if they share the same color code.

Return the maximum amount of money you can rob.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
long long rob(vector<int>& nums, vector<int>& colors) {
int n = nums.size();
vector<long long> res(n, nums[0]);
long long best = 0;
for(int i = 1; i < n; i++) {
res[i] = max(res[i], 1ll * nums[i]);
if(i - 2 >= 0) best = max(best, res[i-2]);
res[i] = max(res[i], nums[i] + best);
if(colors[i] != colors[i-1]) {
res[i] = max(res[i], nums[i] + res[i-1]);
best = max(best, res[i-1]);
}
}
return *max_element(begin(res), end(res));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/house-robber-v/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.