Leetcode 213. House Robber II

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/86702725

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

1. Description

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/
展开阅读全文

没有更多推荐了,返回首页