Leetcode 213. House Robber II

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值