Problem
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.
Algorithm
Dynamic Programming (DP). It can be divided into two cases: one from house 1 to house n-1, and the other from house 2 to house n. Define the state as dp(i), representing the maximum value obtained when selecting house i as the last one. The state transition is defined as dp(i) = max(dp(i-2), dp(i-3)) + nums(i).
Code
class Solution:
def rob(self, nums: List[int]) -> int:
nlen = len(nums)
if nlen < 3:
return max(nums)
dp1 = [0] * nlen
dp1[0], dp1[1] = nums[0], nums[1]
for i in range(2, nlen-1):
if i > 2:
dp1[i] = max(dp1[i-3], dp1[i-2]) + nums[i]
else:
dp1[i] = dp1[i-2] + nums[i]
max1 = max(dp1[0:nlen-1])
dp2 = [0] * nlen
dp2[1], dp2[2] = nums[1], nums[2]
for i in range(3, nlen):
if i > 2:
dp2[i] = max(dp2[i-3], dp2[i-2]) + nums[i]
else:
dp2[i] = dp2[i-2] + nums[i]
max2 = max(dp2[1:nlen])
return max(max1, max2)