198. loot
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, 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.
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if (n <= 1) return n == 0 ? 0 : nums[0];
int[] memo = new int[n];
memo[0] = nums[0];
memo[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < n; i++)
memo[i] = Math.max(memo[i - 1], nums[i] + memo[i - 2]);
return memo[n - 1];
}
}