Likou-198 Robbery
1. Topic
198. Robbery
You are a professional thief planning to steal houses along the street. There is a certain amount of cash hidden in each room. The only restrictive factor that affects your theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by thieves on the same night, the system will automatically call the police. .
Given an array of non-negative integers representing the amount stored in each house, calculate the maximum amount you can steal in one night without triggering the alarm .
Example 1:
输入:[1,2,3,1]
输出:4
解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
2. Analysis
- topic. Seeing this topic, the first thing that comes to mind is that they cannot be adjacent , so if we want to steal
i
one of them, then we need to consider that the previous onei-1
cannot be stolen, andi-2
the other one can be stolen , so we can probably know that this is a dynamic programming problem . - According to the above analysis, dp[i] is the maximum amount when we steal the current i house. Then we can deduce the formula as: dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]).
- initialization. According to the deduction formula, it is obvious that the two numbers in front of dp are needed, so dp[0] and dp[1] are what we need.
- traverse. Start with the 2nd and work backwards.
3. Code and comments
class Solution {
public int rob(int[] nums) {
// 1. dp[i]表示到第i个房间能够偷窃的最高金额
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int[] dp = new int[nums.length + 1];
// 2. 因为递推公式需要dp前两个数,需初始化
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < nums.length; i++){
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[nums.length - 1];
}
}
4. Practice
Link to link to the topic : 198. Robbery