周练(7)213. 打家劫舍 II

#
# @lc app=leetcode.cn id=213 lang=python3
#
# [213] 打家劫舍 II
#

# @lc code=start
class Solution:
    def rob(self, nums: List[int]) -> int:
        def my_rob(nums):
            cur, pre = 0, 0
            for num in nums:
                cur, pre = max(pre + num, cur), cur
            return cur
        return max(my_rob(nums[:-1]), my_rob(nums[1:])) if len(nums) != 1 else nums[0]

# @lc code=end
  • c++版本
/*
 * @lc app=leetcode.cn id=213 lang=cpp
 *
 * [213] 打家劫舍 II
 */

// @lc code=start
class Solution {
public:
    int rob(vector<int>& nums) {
        int nlen = nums.size();
        if (nlen == 0) 
        {
            return 0;
        }
        if (nlen == 1)
        {
            return nums[0];
        }
        return max(my_rob(nums, 0, nlen-1), my_rob(nums, 1, nlen));
    }

    int my_rob(vector<int>& nums, int start, int end)
    {
        int cur = 0,  pre = 0;
        for (int i = start; i < end; i++)
        {
            int t = cur;
            cur = max(pre + nums[i], cur);
            pre = t;
        }
        return cur;
    }
};
// @lc code=end

posted @ 2020-10-15 16:21  douzujun  阅读(105)  评论(0编辑  收藏  举报