You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that 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.code
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.element
难度:easyit
题目:
一个专业的盗贼计划抢一条街。每间门店都有必定的现金,可是每两个相邻的店铺都有链接的安全系统,若是在一晚个上同时抢了两个相邻的店铺则会触发警报,则抢劫行动结束。io
给出一组非负整数表明每间店铺的现金数,盗贼如何在不触发警报的状况下得到最多的钱。ast
思路:
递归, 问题拆分,求最大盗取金额即为class
g1 = num[n] + f(n - 2) (盗取第n家店) g2 = f(n - 1) (不盗取第n家店) f(n) = Max(g1, g2)
依次递推。可用递归实现。 但这种实现会超时。
基于递归相法简化问题,转由迭代实现。im
Runtime: 3 ms, faster than 99.40% of Java online submissions for House Robber.call
class Solution { public int rob(int[] nums) { // nums = null if (null == nums || nums.length < 1) { return 0; } // only 1 element if (1 == nums.length) { return nums[0]; } // iterate int prev = 0, next = nums[0], curVal = next; for (int i = 1; i < nums.length; i++) { curVal = Math.max(next, nums[i] + prev); prev = next; next = curVal; } return next; } }