链接:LintCode 炼码 - ChatGPT!更高效的学习体验!
题解:九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
处理循环数组问题:分类,重复,取反
class Solution {
public:
/**
* @param nums: An array of non-negative integers.
* @return: The maximum amount of money you can rob tonight
*/
int houseRobber2(vector<int> &nums) {
// write your code here
if (nums.size() <= 0) {
return 0;
}
if (nums.size() == 1) {
return nums[0];
}
// max(不要最后一个房子位置, 不要第一个房子位置)
return max(calc(nums, 0, nums.size()-2), calc(nums, 1, nums.size()-1));
}
private:
int calc(const std::vector<int>& nums, int begin, int end) {
std::vector<int> dp(nums.size()+2, 0);
dp[begin+1] = nums[begin];
for (int i = begin+1; i <= end+1; ++i) {
dp[i+1] = max(dp[i], dp[i-1] + nums[i]);
}
return dp[end+1];
}
};