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)
  • 相关阅读:
    codeforces 652B z-sort(思维)
    poj 3268 Silver Cow Party(最短路)
    POJ 2243:Knight Moves(BFS)
    POJ 1107:W's Cipher(模拟)
    POJ 1008 Maya Calendar(模拟)
    Hdu3436-Queue-jumpers(伸展树)
    主席树的另一种写法
    Hdu5785-Interesting(回文串处理)
    Hdu5008-Boring String Problem(后缀数组)
    RMQ模板
  • 原文地址:https://www.cnblogs.com/qianyuesheng/p/9231712.html
Copyright © 2011-2022 走看看