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.
Solution: use the idea of dynamic programming. use dp[i] to represent the max sum of non-adjacent numbers till i. the formula is dp[i]=max(dp[i-2]+nums[i],dp[i-1]), the initial is dp[0]=nums[0],dp[1]=max(nums[0],nums[1]). Here we only need dp[i-2] and dp[i-1] to get dp[i], so we can use two variants dp_pre2 and dp_pre1 to replace the dp array.
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 int size=nums.size(); 5 if (size==0) return 0; 6 if (size==1) return nums[0]; 7 int dp_pre2=nums[0]; 8 int dp_pre1=max(nums[0],nums[1]); 9 for (int i=2;i<size;i++){ 10 int temp=max(dp_pre2+nums[i],dp_pre1); 11 dp_pre2=dp_pre1; 12 dp_pre1=temp; 13 } 14 return dp_pre1; 15 } 16 };
])