You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
class Solution {
public int rob(int[] nums) {
int ppreMax = 0;
int preMax = nums[0];
int max = preMax;
for (int i = 1; i < nums.length; ++i) {
int tmp = Math.max(ppreMax, preMax); // most important
ppreMax += nums[i];
max = Math.max(ppreMax, preMax);
// calculate preMax and ppreMax
int t = ppreMax;
ppreMax = tmp;
preMax = t;
}
return max;
}
}
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Example 2:
简单的线性DP问题。我的思路是创建一个一维dp数组,dp[i]表示如果要抢劫第i个房子,此时抢夺的最大金钱数是多少。转移状态函数是dp[i] = Math.max(dp[i], dp[j] + nums[i])。(j < i)
然而这样的空间复杂度是O(n),但时间复杂度变为了平方级别(感觉这跟我之前做的线性DP犯的小问题一致)。我们可以换个角度去理解,dp[i]表示0~i的最大抢劫数,dp[i]可以分为抢劫第i个房子状态和不抢劫第i个房子状态,那么转移函数就是dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i])。
继续优化,减少空间复杂度:只使用两个变量就可以分别保存前一个值(dp[i - 1])和前两个值dp[i - 2]。
时隔两年后又重新做了这道题。
关键在于:
如何判断下一轮的ppreMax。
解法如下:(ppreMax表示不包括nums[i]的之前的和的最大值,preMax表示包括nums[i]的之前的和最大值)
参考资料:
The text was updated successfully, but these errors were encountered: