#3840
Medium Algorithms House robber v
Array Dynamic Programming
53.9% acceptance
Mar 15, 2026
72
2
You are given two integer arrays nums and colors, both of length n.
You cannot rob two adjacent houses if they share the same color code.
Return the maximum amount of money you can rob.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn rob(nums: Vec<i32>, colors: Vec<i32>) -> i64 {
let n = nums.len();
if n == 0 { return 0; }
let mut not_rob = 0i64;
let mut rob = nums[0] as i64;
for i in 1..n {
let new_not_rob = not_rob.max(rob);
let new_rob = if colors[i] != colors[i - 1] {
not_rob.max(rob) + nums[i] as i64
} else {
not_rob + nums[i] as i64
};
not_rob = new_not_rob;
rob = new_rob;
}
not_rob.max(rob)
}
}