213. House Robber II
Problem description:
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 security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: [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: [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.
Solution:
This problem is pretty similar to 198. House Robber. First, let’s look at the example [1,2,3,1]
. If you choose to rob nums[0]
, then you must not rob nums[size-1]
, and your right boundary would be nums[size-2]
. On the other hand, if you choose to rob nums[size-1]
, then you must not rob nums[0]
, that means you could only start robbing from nums[1]
.
- rob nums[0]:
0...n-2
- not rob nums[0]:
1...n-1
Therefore, we can either separate the array into two different array or we can do the search twice.
In previous question, 198. House Robber, we use a simple for loop to do the dynamic programming. We can further extract the for loop as a helper function, which takes left and right boundary as input.
If you don’t want to build another function, you can use for loop twice as well, like solution 2.
1 | class Solution: |
1 | class Solution { |
1 | class Solution { |
Improvement
Slicing a list is actually $O(n)$ space in Python. In our case, nums[1:]
, nums[:-1]
create copies, to avoid this, we can pass indices into the simple_rob
function instead of sliced lists. Below is the less elegant, but true $O(1)$ space solution: