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)