leetcode - 213. 打家劫舍 II

leetcode - 213. 打家劫舍 II

题目

leetcode - 213. 打家劫舍 II_第1张图片

代码

#include 
#include 
using namespace std;

int robMoney(vector<int>& nums, int start, int end){
	int first = nums[start], second = max(nums[start], nums[start+1]);
	for(int i = start + 2; i <= end; i++){
		int temp = second;
		second = max(nums[i] + first, second);
		first = temp;
	}
	return second;
}

int rob(vector<int>& nums) {
	int n = nums.size();
	if(n == 1){
		return nums[0];
	}else if(n == 2){
		return max(nums[0], nums[1]);
	}
	return max(robMoney(nums, 0, n-2), robMoney(nums, 1, n-1));
}

int main(){
	int n, res;
	cin>>n;
	vector<int> nums(n);
	for(int i = 0; i < n; i++){
		cin>>nums[i];
	}
	res = rob(nums);
	cout<<res;
    return 0;
}

你可能感兴趣的:(刷题,leetcode,c++)