House Robber II

House Robber 2 – Medium Level Problem

You are given an array of integers nums, where nums[i] represents the amount of money in the (i)th house. The houses are arranged in a circle, meaning the first and last houses are neighbors.

You plan to rob some houses, but you cannot rob two adjacent houses because doing so will trigger the security system and alert the police.

Your task is to find the maximum amount of money you can rob without triggering the security system.

House Robber 2 Problem

Explanation:

  • You can’t rob nums[0] + nums[2] = 6 because nums[0] and nums[2] are adjacent houses.
  • Maximum you can rob is nums[1] = 4.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

Algorithm for Solving House Robber 2 Problem

1. Handle Edge Cases:

If there’s only one house, return its value. If there are two houses, return the maximum of the two.

2. Divide into Two Scenarios:

  • Scenario 1: Consider houses from the first to the second-last.
  • Scenario 2: Consider houses from the second to the last.

3. Use the House Robber Algorithm:

Apply the regular House Robber approach (linear) to calculate the maximum money for both scenarios.

4. Compare Results:

Take the maximum value between the two scenarios.

5. Return the Result:

The maximum value is the most money you can rob without alerting the police.

House Robber 2 Solution

There are mainly 4 approach to solve this problem-

  1. Recursion Method
  2. Dynamic Programming Top Down Method
  3. Dynamic Programming Bottom Up Method
  4. Dynamic Programming Space Optimized Method

1. Recursion Method

Solve the problem by splitting it into two cases—robbing houses excluding the first or excluding the last—then use recursion to find the maximum money in each case.

  • Time complexity: O(2^n)
  • Space complexity: O(n)

Code

2. Dynamic programming Top Down Method

Combine recursion with memorization to handle the circular arrangement of houses, storing intermediate results for both cases to avoid overlapping calculations.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

3. Dynamic Programming Bottom Up Method

Break the problem into two linear scenarios (excluding first or last house) and calculate maximum money iteratively by building from smaller sub problems.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

4. Dynamic Programming Space Optimized Method

Simplify the Bottom-Up approach by keeping track of only the last two states for each scenario, minimizing memory usage while solving for both cases.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles