Leetcode of dynamic programming (DP) Thematic -198. Loot (House Robber)

Leetcode of dynamic programming (DP) Thematic -198. Loot (House Robber)


 

You are a professional thief to steal street plan of the house. Each room are in possession of some cash, the only constraints affecting steal your neighbor's house is equipped with anti-theft system communicate with each other, if two adjacent houses on the same night, thieves broke into the system will automatically alarm .

Given a representative from each non-negative integer array of Housing storage amount calculated in case you do not touch the alarm device, you can steal the maximum amount to.

Example 1:

Input: [1,2,3,1] 
Output: 4 
Explanation: Housing theft No. 1 (amount = 1), then the theft Housing 3 (amount = 3). 
     The maximum amount to theft = 3 + 1 = 4.

Example 2:

Input: [2,7,9,3,1] 
Output: 12 
Explanation: Housing theft No. 1 (amount = 2), 3 theft Housing (amount = 9), followed by theft No. 5 Housing (amount = 1). 
     The maximum amount to theft = 2 + 9 + 1 = 12.

Defined DP: 
DP [i] [0] indicates the i-steal without the house
DP [i] [1] indicates the i-th house stealing case

not stolen can be divided into two situations:
  1, nor stolen between the first i-1 house
  2, between the first and stole house i-1, i-between can steal the

stolen case: between the first i-1 did not steal, steal and the i-th inter-

state transition equation:
DP [I] [0] = Math.max (DP [-I. 1] [0], DP [-I. 1] [. 1]); 
DP [I] [. 1] DP = [-I. 1] [0] + nums [i];

and issues like stock.
class Solution {
    public int rob(int[] nums) {
        if(nums==null || nums.length==0) return 0;
        int[][] dp = new int[nums.length][2];
        dp[0][0] = 0;
        dp[0][1] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]);
            dp[i][1] = dp[i-1][0] + nums[i];
        }
        return Math.max(dp[nums.length-1][0],dp[nums.length-1][1]);
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11487848.html