Title description
At first glance, I know that this problem has to be done with dynamic programming. I learned it in school, but I lacked practice and almost forgot the theoretical knowledge. I still don’t know how to use dp to solve this problem. I can only look at the solution. , And write the code independently after understanding the
dp equation as follows:
dp[i] = max(dp[i-2] + nums[i] , dp[i-1])
- dp[i] represents the maximum benefit obtained when i’s home is stolen
- nums[i] indicates how much money is currently in the house to be stolen
It is understood that after stealing i’s house, the maximum benefit I get is either equal to the income of the previous house (not stealing the current house), or equal to the sum of the amount of stealing i-2 house and the current house (stealing the current house) this home)
int rob(vector<int>& nums) {
if(nums.size() == 0) return 0;//没有房屋
if(nums.size() == 1) return nums[0];//只有一间房屋
int len = nums.size();
vector<int> dp(len);
dp[0] = nums[0];//偷了第0家
for(int i=1; i<len; i++){
if(i == 1){
dp[i] = max(nums[i] , dp[i-1]);//偷第1家
}else{
dp[i] = max(dp[i-2] + nums[i] , dp[i-1]);
}
}
return dp[len-1];
}
Optimize, you can remove the dp array. Since the dp array only records the maximum income currently obtained, just find a variable and record it. Of course, dp[i-2] in the above code must also be recorded with variables
int rob(vector<int>& nums) {
if(nums.size() == 0) return 0;
if(nums.size() == 1) return nums[0];
if(nums.size() == 2) return nums[0] > nums[1] ? nums[0] : nums[1];//只有两个房屋时
int len = nums.size();
int cur_profit;
int pre_2 = nums[0];//dp[i-2]
int pre_1 = nums[0] > nums[1] ? nums[0] : nums[1];//dp[i-1]
for(int i=2; i<len; i++){
cur_profit = max(pre_2 + nums[i] , pre_1);
pre_2 = pre_1;
pre_1 = cur_profit;
}
return cur_profit;
}