House Robbery II

Definition

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.

Example 2:

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 3:

Input: nums = [1,2,3]
Output: 3

Intuition

For this question, it's important to reduce it to House Robbery

As we can see, since we cannot rob the first and the last house together, our problem becomes finding the max of either

  • Robbing from house [1, n]
  • Robbing from house [0, n - 1]

There fore we can implement House Robbery from [1, n] and [0, n-1] and find the max

Implementation

class App:
    def rob(self, nums: List[int]) -> int:
        if not nums: return 0
        if len(nums) <= 2: return max(nums)

        self.nums = nums

        return max(
            self.robHouse(0, len(nums) - 2),  
            self.robHouse(1, len(nums) - 1)
        )

    def robHouse(self, start, end): # end inclusive
        values = [0] * (end - start + 1)

        values[0] = self.nums[start]
        values[1] = max(values[0], self.nums[start + 1])

        for i in range(2, len(values)):
            values[i] = max(
                values[i - 2] + self.nums[start + i],
                values[i - 1]
            )

        return values[-1]

Time complexity: $O(n + n) = O(n)$
Space complexity: $O(n + n) = O(n)$

[!note]
We can further optimise space to $O(1)$ by following House Robbery > Optimisation