文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
House Robber II2. Solution
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n == 0) {
return 0;
}
int pre1 = 0;
int pre2 = 0;
int current = 0;
int maximum = nums[0];
for(int i = 0; i < n - 1; i++) {
pre1 = pre2;
pre2 = current;
current = max(pre1 + nums[i], pre2);
}
maximum = max(current, maximum);
pre1 = 0;
pre2 = 0;
current = 0;
for(int i = 1; i < n; i++) {
pre1 = pre2;
pre2 = current;
current = max(pre1 + nums[i], pre2);
}
maximum = max(current, maximum);
return maximum;
}
};
网友评论