文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 213. House Robber II

2. 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;
    }
};

Reference

  1. https://leetcode.com/problems/house-robber-ii/description/

相关文章:

  • 2021-07-08
  • 2022-12-23
  • 2021-06-29
  • 2021-11-29
猜你喜欢
  • 2021-08-11
  • 2021-10-27
  • 2021-09-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
相关资源
相似解决方案