[leetcode/lintcode 题解] 打劫房屋 · H
2020-05-29 本文已影响0人
SunnyZhao2019
【题目描述】
假设你是一个专业的窃贼,准备沿着一条街打劫房屋。每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警。
给定一个非负整数列表,表示每个房子中存放的钱, 算一算,如果今晚去打劫,在不触动报警装置的情况下, 你最多可以得到多少钱 。
在线评测地址:
https://www.lintcode.com/problem/house-robber/?utm_source=sc-js-mh0529
【样例】
样例 1:
<pre>输入: [3, 8, 4]
输出: 8
解释: 仅仅打劫第二个房子.</pre>
样例 2:
<pre>输入: [5, 2, 1, 3]
输出: 8
解释: 抢第一个和最后一个房子</pre>
【题解】
线性DP题目.
设 dp[i] 表示前i家房子最多收益, 答案是 dp[n], 状态转移方程是
dp[i] = max(dp[i-1], dp[i-2] + A[i-1])
考虑到dp[i]的计算只涉及到dp[i-1]和dp[i-2], 因此可以O(1)空间解决.
<pre>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];
}
}
//////////// 空间复杂度O(1)版本
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];
}
</pre>
【更多题解参考】
https://www.jiuzhang.com/solution/house-robber/?utm_source=sc-js-mh0529