198.House Robber (DP)

Source: Internet
Author: User

You is a professional robber planning to rob houses along a street. Each house have a certain amount of money stashed, the only constraint stopping all from robbing each of the them are that Adjac ENT houses have security system connected and it would automatically contact the police if the adjacent houses were broken Into on the same night.

Given a list of non-negative integers representing the amount of money in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.

Example 1:

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.

Example 2:

Input: [2,7,9,3,1]
Output:12
Explanation:rob House 1 (money = 2), Rob House 3 (Money = 9) and Rob House 5 (Money = 1).
Total amount you can Rob = 2 + 9 + 1 = 12.

class Solution:    def rob(self, nums):        """        :type nums: List[int]        :rtype: int        """        dp = [0 for i in range(len(nums))]        if len(nums)==0:            return 0        if len(nums)==1:            return nums[0]        dp[0] = nums[0]        dp[1] = max(nums[0],nums[1])        for i in range(2,len(nums)):            if dp[i-1]==dp[i-2]:                dp[i] = dp[i-1] + nums[i]            else:                dp[i] = max(dp[i-1],dp[i-2]+nums[i])        return dp[-1]

If the DP idea is not good, you can try to start from the first, write a few more to find the law, write the state transfer equation.

198.House Robber (DP)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.