LeetCode #3840 — MEDIUM

House Robber V

Move from brute-force thinking to an efficient approach using core interview patterns strategy.

Solve on LeetCode
The Problem

Problem Statement

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:

  • 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 <= 105
  • 1 <= nums[i], colors[i] <= 105

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: General problem-solving

Example 1

[1,4,3,5]
[1,1,2,2]

Example 2

[3,1,2,4]
[2,3,2,2]

Example 3

[10,1,3,9]
[1,1,1,2]

Related Problems

  • House Robber (house-robber)
Step 02

Core Insight

What unlocks the optimal approach

  • Use dynamic programming
  • Let <code>dp[i]</code> be the maximum money robbable considering houses up to index <code>i</code>
  • Initialize <code>dp[i]</code> with <code>nums[i]</code>, then compare with skipping the house: <code>dp[i - 1]</code>
  • If <code>colors[i] != colors[i - 1]</code>, allow taking adjacent house: <code>nums[i] + dp[i - 1]</code>
  • Always allow non-adjacent take: <code>nums[i] + dp[i - 2]</code>
  • Answer is <code>dp[n - 1]</code>
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3840: House Robber V
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3840: House Robber V
// package main
// 
// // https://space.bilibili.com/206214
// func rob1(nums, colors []int) int64 {
// 	n := len(nums)
// 	f := make([]int, n+1)
// 	f[1] = nums[0]
// 	for i := 1; i < n; i++ {
// 		if colors[i] != colors[i-1] {
// 			f[i+1] = f[i] + nums[i]
// 		} else {
// 			f[i+1] = max(f[i-1]+nums[i], f[i]) // 选或不选
// 		}
// 	}
// 	return int64(f[n])
// }
// 
// func rob(nums, colors []int) int64 {
// 	n := len(nums)
// 	f0, f1 := 0, nums[0]
// 	for i := 1; i < n; i++ {
// 		if colors[i] != colors[i-1] {
// 			f0 = f1
// 			f1 += nums[i]
// 		} else {
// 			f0, f1 = f1, max(f0+nums[i], f1)
// 		}
// 	}
// 	return int64(f1)
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.

OPTIMIZED
O(n) time
O(1) space

Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.

Shortcut: If you are using nested loops on an array, there is almost always an O(n) solution. Look for the right auxiliary state.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.