LeetCode-in-Java

3840. House Robber V

Medium

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 ith 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.

Example 1:

Input: nums = [1,4,3,5], colors = [1,1,2,2]

Output: 9

Explanation:

Example 2:

Input: nums = [3,1,2,4], colors = [2,3,2,2]

Output: 8

Explanation:

Example 3:

Input: nums = [10,1,3,9], colors = [1,1,1,2]

Output: 22

Explanation:

Constraints:

Solution

public class Solution {
    public long rob(int[] nums, int[] colors) {
        int n = nums.length;
        long dp0 = 0;
        long dp1 = nums[0];
        for (int i = 1; i < n; i++) {
            long new0;
            long new1;
            if (colors[i] == colors[i - 1]) {
                new1 = dp0 + nums[i];
                new0 = Math.max(dp0, dp1);
            } else {
                new0 = Math.max(dp1, dp0);
                new1 = Math.max(dp0, dp1) + nums[i];
            }
            dp0 = new0;
            dp1 = new1;
        }
        return Math.max(dp0, dp1);
    }
}