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)
  • 相关阅读:
    UVa10917
    T^T online judge 2952
    AcWing 105.七夕祭
    AcWing 99.激光炸弹(二维前缀和)
    AcWing 97.约数之和
    AcWing 95. 费解的开关
    ccf/csp 2018 12 小明放学
    BNUOJ 33535 Final Exam Arrangement
    分块
    sublime安装配置
  • 原文地址:https://www.cnblogs.com/qianyuesheng/p/9231712.html
Copyright © 2011-2022 走看看