zoukankan      html  css  js  c++  java
  • 213. House Robber II

    Description:

    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 security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
    
    Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
    

     

    Example 1:

    Input: [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: [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.
    

    Sulotions:

    class Solution:
        def rob(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if len(nums) == 0:
                return 0
            if len(nums) == 1:
                return nums[0]
            if len(nums) == 2:
                return max(nums[0], nums[1])
            dp= dp2 = [0]*len(nums)
            older = nums[0]
            old = max(older, nums[1])
            # 不能同时抢第一家和最后一家
            answer1 = old
            for i in range(2, len(nums)-1):
                new = max(older + nums[i], old)
                answer1 = new
                older = old
                old = new
            older2 = nums[1]
            old2 = max(older2, nums[2])
            answer2 = old2
            for j in range(3, len(nums)):
                new2 = max(older2+ nums[j], old2)
                answer2 = new2
                older2 = old2
                old2 = new2
            return max(answer1, answer2)
  • 相关阅读:
    题解-CmdOI2019 口头禅
    题解-NOI2003 智破连环阵
    题解-CF1282E The Cake Is a Lie
    CF1288F Red-Blue Graph
    题解-洛谷P4229 某位歌姬的故事
    莫比乌斯反演
    [HNOI2008]越狱(bzoj1008)(组合数学+正难则反)
    [FJOI2007]轮状病毒(bzoj1002)(递推+高精度)
    矩阵快速幂
    高斯消元
  • 原文地址:https://www.cnblogs.com/qianyuesheng/p/9231712.html
Copyright © 2011-2022 走看看