[Leetcode/lintcode solution to a problem] House Robber of loot building ·

[Thematic description]

Assume you are a professional thief, prepare along building of loot of a street. Every house is depositing the money of specific amount. The only obligation requirement that you face is: The house of photograph adjacent is installing the system of guard against theft of mutual connection, and? Two houses when photograph adjacent are same day by loot when, this system can call the police automatically.

Give list of negative integer of a blame, represent the fund that deposits in every house, calculate, if go tonight loot, Below the case that does not move warning decice, you can get how many money at most.

Online evaluation address:

Https://www.lintcode.com/problem/house-robber/ ? Utm_source=sc-v2ex-fks0529

[Sample]

Sample 1:

 Shu  Ru : [3, 8, 4]
 Shu  Chu : 8
 Jie  Shi :  Jin  Jin  Da  Jie  Di  Er  Ge  Fang  Zi 

Sample 2:

 Shu  Ru : [5, 2, 1, 3] 
 Shu  Chu : 8
 Jie  Shi :  Qiang  Di  Yi  Ge  He  Zui  Hou  Yi  Ge  Fang  Zi 

[Solution to a problem]

Linear DP title.

Building of before setting Dp[i] to express Home I is most accrual, the answer is Dp[n] , state move equation is

Dp[i] = Max(dp[i-1] , dp[i-2] + A[i-1] )

The computation that considers Dp[i] involves Dp[i-1] and Dp[i-2] only, because this is OK,O(1) space is solved.

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) {
        int n = A.length;
        if (n == 0)
            return 0;
        long []res = new long[n+1];

        res[0] = 0;
        res[1] = A[0];
        for (int i = 2; i <= n; i++) {
            res[i] = Math.max(res[i-1], res[i-2] + A[i-1]);
        }
        return res[n];
    }
}

////////////  Kong  Jian  Fu  Za  Du  O(1) Ban  Ben 

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) {
        int n = A.length;
        if (n == 0)
            return 0;
        long []res = new long[2];

        res[0] = 0;
        res[1] = A[0];
        for (int i = 2; i <= n; i++) {
            res[i%3] = Math.max(res[(i-1)%2], res[(i-2)%2] + A[i-1]);
        }
        return res[n%2];
    }    

[More solution to a problem is referenced]

Https://www.jiuzhang.com/solution/house-robber/ ? Utm_source=sc-v2ex-fks0529

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *