problem
solution1:
code
class Solution { public: int rob(vector<int>& nums) { int pre = 0; int cur = 0; for(int i=0; i<nums.size(); i++) { int tmp = max(pre+nums[i], cur); pre = cur; cur = tmp; } return cur; } };
solution2:
M(k) = money at the kth house P(0) = 0 P(1) = M(1) P(k) = max(P(k−2) + M(k), P(k−1))
code
class Solution { public: int rob(vector<int>& nums) { if(nums.size()==0) return 0; if(nums.size()==1) return nums[0]; if(nums.size()==2) return max(nums[0], nums[1]); vector<int> f(nums.size(), 0); f[0] = nums[0]; f[1] = max(nums[0], nums[1]); for(int i=2; i<nums.size(); i++) { f[i] = max(f[i-2]+nums[i], f[i-1]); } return f[nums.size()-1]; } };