打劫房屋
题目
假设你是一个专业的窃贼,准备沿着一条街打劫房屋。每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警。
给定一个非负整数列表,表示每个房子中存放的钱, 算一算,如果今晚去打劫,你最多可以得到多少钱 在不触动报警装置的情况下。
样例
给定 [3, 8, 4], 返回 8.
挑战
O(n) 时间复杂度 且 O(1) 存储。
题解
动态规划,就是选择从第1个房间还是第2个房间开始,定义一个长度为2的数组保存变量。第i个房屋是否打劫要看res[(i-1)%2]和res[(i-2)%2]+ A[i]谁更大。
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;
long []res = new long[2];
if(n==0)
{
return 0;
}
if(n >= 1)
{
res[0] = A[0];
}
if(n >= 2)
{
res[1] = Math.max(A[0], A[1]);
}
if(n > 2)
{
for(int i = 2; i < n; i++)
{
res[i%2] = Math.max(res[(i-1)%2], res[(i-2)%2]+ A[i]);
}
}
return res[(n-1)%2];
}
}
Last Update 2016.11.13