SDE & MLE Prep

213. House Robber II

Problem

Same as House Robber, but the houses stand in a circle, so the first and last houses are adjacent too.

Example: [2,3,2] → 3; [1,2,3,1] → 4

Circle → the first and last houses can't both be robbed. Answer = max(rob(nums[1:]), rob(nums[:-1])) (single house: itself).

Complexity: O(n) time, O(1) space.

class Solution:
    def rob(self, nums: List[int]) -> int:
        def line(arr):
            prev = cur = 0
            for x in arr:
                prev, cur = cur, max(cur, prev + x)
            return cur

        if len(nums) == 1:
            return nums[0]
        return max(line(nums[1:]), line(nums[:-1]))