House Robber V Problem
Description
LeetCode Problem 3840.
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.
Example 1:
Input: nums = [1,4,3,5], colors = [1,1,2,2]
Output: 9
Explanation:
- Choose houses i = 1 with nums[1] = 4 and i = 3 with nums[3] = 5 because they are non-adjacent.
- Thus, the total amount robbed is 4 + 5 = 9.
Example 2:
Input: nums = [3,1,2,4], colors = [2,3,2,2]
Output: 8
Explanation:
- Choose houses i = 0 with nums[0] = 3, i = 1 with nums[1] = 1, and i = 3 with nums[3] = 4.
- This selection is valid because houses i = 0 and i = 1 have different colors, and house i = 3 is non-adjacent to i = 1.
- Thus, the total amount robbed is 3 + 1 + 4 = 8.
Example 3:
Input: nums = [10,1,3,9], colors = [1,1,1,2]
Output: 22
Explanation:
- Choose houses i = 0 with nums[0] = 10, i = 2 with nums[2] = 3, and i = 3 with nums[3] = 9.
- This selection is valid because houses i = 0 and i = 2 are non-adjacent, and houses i = 2 and i = 3 have different colors.
- Thus, the total amount robbed is 10 + 3 + 9 = 22.
Constraints:
1 <= n == nums.length == colors.length <= 10^51 <= nums[i], colors[i] <= 10^5
Solution
Approach: Dynamic Programming
Keep two values while scanning the houses: f is the best total so far when the current house is not robbed, and g is the best total when it is robbed. Start with f = 0 and g = nums[0].
For the next house i, the new f is always max(f, g), because skipping house i leaves us free to have robbed or skipped the previous one. The new g depends on the colors:
- If houses
i - 1andihave the same color, we may not have robbedi - 1, sog = f + nums[i]. - Otherwise there is no restriction, so
g = max(f, g) + nums[i].
Update both values together using the old f and g. The answer is max(f, g) after the last house. The total can reach 10^10, so use 64-bit integers.
Complexity:
- Time:
O(n). - Space:
O(1).
class Solution:
def rob(self, nums: List[int], colors: List[int]) -> int:
n = len(nums)
f, g = 0, nums[0]
for i in range(1, n):
if colors[i - 1] == colors[i]:
f, g = max(f, g), f + nums[i]
else:
f, g = max(f, g), max(f, g) + nums[i]
return max(f, g)