Robbery LeetCode 198 (sequence type DP)
You are a professional thief to steal street plan of the house. Each room are in possession of some cash, the only constraints affecting steal your neighbor's house is equipped with anti-theft system communicate with each other, if two adjacent houses on the same night, thieves broke into the system will automatically alarm .
Given a representative from each non-negative integer array of Housing storage amount calculated in case you do not touch the alarm device, can steal the maximum amount to.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Housing theft No. 1 (amount = 1), then the theft Housing 3 (amount = 3).
The maximum amount to theft = 3 + 1 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Housing theft No. 1 (amount = 2), 3 theft Housing (amount = 9), followed by theft No. 5 Housing (amount = 1).
The maximum amount to theft = 2 + 9 + 1 = 12.
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/house-robber
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Thinking
Whether the i-th rob the house, depending on the state of the front of the house (which is the maximum value that can be obtained in front of the house)
- If you do not grab the i-th, the greatest value is the first i-1 [home] can get the most value
- If you grab the i-th, then the first i-1 family can not grab the biggest value is the maximum value of the previous [i-2 family can obtain the value of the i-th + grab obtained]
Defined state / transition state
- Defined dp [i] represents the maximum value that can be obtained former home i
- dp[i] = max( dp[i-2]+value[i],dp[i-1] )
Code
#define max(a, b) ((a>b)?(a):(b))
class Solution {
public:
int dp[114514];
int rob(vector<int>& nums)
{
int len = nums.size();
if(len == 0)
{
return 0;
}
dp[0] = 0;
dp[1] = nums[0];
for(int i=2; i<=len; i++)
{
int index = i - 1;
dp[i] = max(dp[i-2]+nums[index], dp[i-1]);
}
return dp[len];
}
};