https://leetcode.com/problems/house-robber-ii/
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.
variation of https://leetcode.com/problems/house-robber/
newly added constraint: arranged in a circle
I just splitted the possible cases not voilating the contraint.
case 1. case of nums
which reduced to [1:]
case 2. case of nums
which recuded to [:-1]
And then take the maxium value in case 1 and case 2.
class Solution:
def f(self, memo, i, nums, n):
if (i >= n):
return 0
if (i in memo): return memo[i]
ans = max(
nums[i] + self.f(memo, i+2, nums, n),
self.f(memo, i+1, nums, n)
)
memo[i] = ans
return ans
def rob(self, nums: List[int]) -> int:
n = len(nums)
if n == 1: return nums[0]
ans1 = self.f({}, 0, nums[1:], n-1)
ans2 = self.f({}, 0, nums[:-1], n-1)
return max(ans1, ans2)