198. House Robber

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.

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.

难度:easy

题目:
一个专业的盗贼计划抢一条街。每间门店都有一定的现金,但是每两个相邻的店铺都有连接的安全系统,如果在一晚个上同时抢了两个相邻的店铺则会触发警报,则抢劫行动结束。

给出一组非负整数代表每间店铺的现金数,盗贼如何在不触发警报的情况下获得最多的钱。

思路:
递归, 问题拆分,求最大盗取金额即为

g1 = num[n] + f(n - 2) (盗取第n家店)
g2 = f(n - 1) (不盗取第n家店)
f(n) = Max(g1, g2)

依次递推。可用递归实现。 但这种实现会超时。
基于递归相法简化问题,转由迭代实现。

Runtime: 3 ms, faster than 99.40% of Java online submissions for House Robber.

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;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018056728
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞