Saturday, September 24, 2016

[LintCode] 392 House Robber 解题报告

Description
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
Given [3, 8, 4], return 8.


思路
我们用f[i]来表示抢到第i个房子时能抢到的最多的钱。
注意这里初始值f[0] = 0是指什么都没有抢到时候钱是0。所以之后的index都会往后shift一个。f[i]是表示抢到i - 1这个房子时的最大值
f[i] = Math.max(f[i - 1], f[i - 2] + A[i - 1])
意思是抢到第i - 1个房子时最多的钱,有以下2个值的最大值决定:
1. 抢到上1个房子时的最大值,当前这个房子不抢
2. 抢到上2个房子时的最大值,并且抢当前这个房子
时间复杂度O(n)。空间复杂度O(n)。
空间复杂度要变成O(1)很简单,不用状态数组,用prevPrev,prev,和curr换着来就可以。

Code
public class Solution {
    /**
     * @param A: An array of non-negative integers.
     * return: The maximum amount of money you can rob tonight
     */
    public long houseRobber(int[] A) {
        // write your code here
        if (A.length == 0) {
            return 0;
        }
        
        long[] f = new long[A.length + 1];
        f[0] = 0;
        f[1] = A[0];
        
        for (int i = 2; i < A.length + 1; i++) {
            f[i] = Math.max(f[i - 1], f[i - 2] + A[i - 1]);
        }
        
        return f[A.length];
    }
}



public class Solution {
    /**
     * @param A: An array of non-negative integers.
     * return: The maximum amount of money you can rob tonight
     */
    public long houseRobber(int[] A) {
        // write your code here
        if (A.length == 0) {
            return 0;
        }
        
        long prevPrev = 0;
        long prev = A[0];
        long curr = prev;
        
        for (int i = 1; i < A.length; i++) {
            curr = Math.max(prev, prevPrev + A[i]);
            prevPrev = prev;
            prev = curr;
        }
        
        return curr;
    }
}