House Robber
Question
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]
, return 8
.
Challenge
O(n) time and O(1) memory.
Tags
LinkedIn Dynamic Programming Airbnb
Related Problems
Medium House Robber III 28 % Medium House Robber II 28 % Medium Paint House 35 % Easy Paint Fence 28 % Naive Fibonacci 25 % Easy Climbing Stairs
Analysis
根据 动态规划4要素 进行分析:
类型:序列型动态规划
状态 State
f[i] 表示前i个房子中,偷到的最大价值
方程 Function
f[i] = max(f[i-1], f[i-2] + A[i-1]);
初始化 Intialization
f[0] = 0;
f[1] = A[0];
答案 Answer
f[n]
状态转移方程将f[i]分了两种情况(这里定义i是第i个房子,因此数组下标要减1,使用A[i-1]): 1. 去A[i-1],那么f[i] = f[i-2] + A[i-1] 2. 不去A[i-1],那么f[i] = f[i-1] 两者取最大值就是f[i]
滚动数组优化空间复杂度
因为只与前面两个dp状态有关,因此可以通过滚动数组优化,状态转移方程变为:dp[i%2] = Math.max(dp[(i-1)%2], dp[(i-2)%2] + A[i-1]);
优化后:Space O(1), Time O(n)
Solution
DP Solution(一维序列型动态规划) with O(n) space, O(n) time
DP Solution Optimized with Rolling Array (滚动数组), with O(1) space and O(n) time
Two Variables with O(1) space, O(n) time
Reference
Last updated
Was this helpful?