LeetCode213 打家劫舍 II

LeetCode213 打家劫舍 II

考虑环形,首位不能同时选择

则分别对 \([0, len - 2]\)\([1, len - 1]\)LeetCode198 打家劫舍

class Solution:
    def rob(self, nums: List[int]) -> int:
        def solver(start: int, end: int) -> int:
            first = nums[start]
            second = max(nums[start], nums[start + 1])
            for i in range(start + 2, end + 1):
                first, second = second, max(first + nums[i], second)
            return second
        
        length = len(nums)
        if length == 1:
            return nums[0]
        elif length == 2:
            return max(nums[0], nums[1])
        else:
            return max(solver(0, length - 2), solver(1, length - 1))

posted on 2022-06-30 00:24  solvit  阅读(22)  评论(0编辑  收藏  举报

导航