198 House Robber
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
Given[3, 8, 4]
, return8
.
O(n) time and O(1) memory.
这题因为只能隔着抢,所以我们把前两个初始化。然后从第三个开始看往后怎么抢。dp[0]表示只有一个房子,所以初始化为第一个房子的价值。dp[1]表示我们有两个房子可以抢,抢比较大的那个。然后第三个房子,我们可以考虑:1,抢这家i和i-2家的价值大,还是2,抢i - 1那家人的大。取最大值。
再来一种多开一位的写法:
滚动数组优化,因为现在状态只跟前两个状态有关,所以只要存2个状态,让新的覆盖旧的就ok了。(最少可以用2,用7,8,9也行)
Last updated