#3840

House Robber V

Medium
ArrayDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

We can use dynamic programming to keep track of the maximum money that can be robbed up to each house while respecting the color and adjacency constraints.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[i] represents the maximum money robbed up to house i.
  2. 2Step 2: For each house, decide whether to rob it or skip it based on the previous house's color and amount.
  3. 3Step 3: Return the last element of the DP array as the result.
solution.py11 lines
1def rob(nums, colors):
2    n = len(nums)
3    dp = [0] * n
4    dp[0] = nums[0]
5    for i in range(1, n):
6        dp[i] = dp[i - 1]
7        for j in range(i - 1, -1, -1):
8            if colors[j] != colors[i]:
9                dp[i] = max(dp[i], dp[j] + nums[i])
10                break
11    return max(dp)

Complexity note: The time complexity is quadratic due to the nested loop checking previous houses, while space is linear for the DP array.

  • 1Non-adjacent houses must have different colors.
  • 2Dynamic programming can efficiently track maximum values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.