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.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;
    }
}
相關文章
相關標籤/搜索