Skip to content

Latest commit

 

History

History
80 lines (57 loc) · 2.38 KB

0213. House Robber II.md

File metadata and controls

80 lines (57 loc) · 2.38 KB
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

Constraints:

1 <= nums.length <= 100
0 <= nums[i] <= 1000
class Solution:

   def rob1(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 2:
            return 0 or nums[0]

        dp1 = [0] * (n + 1)  # Rob the first house
        dp2 = [0] * (n + 1)  # Skip the first house

        for i in range(2, n + 1):
            # Rob the first house, can't rob the last house
            dp1[i] = max(dp1[i - 1], dp1[i - 2] + nums[i - 1])
            # Skip the first house, can rob the last house
            dp2[n - i] = max(dp2[n - i + 1], dp2[n - i + 2] + nums[n - i])
        return max(dp1[n], dp2[0])

    def rob2(self, nums: List[int]) -> int:
        if len(nums) < 2:
            return nums[0]
        rob1 = 0
        rob2 = 0
        for n in nums[1:]:
            rob1, rob2 = rob2, max(rob1 + n, rob2)

        rob3 = 0
        rob4 = 0
        for n in nums[:-1]:
            rob3, rob4 = rob4, max(rob3 + n, rob4)
        return max(rob2, rob4)

    def rob3(self, nums: List[int]) -> int:
        def helper(nums):
            rob1, rob2 = 0, 0

            for n in nums:
                rob1, rob2 = rob2, max(rob1 + n, rob2)
            return rob2

        return max(nums[0], helper(nums[1:]), helper(nums[:-1]))