美文网首页Leetcode
Leetcode 213. House Robber II

Leetcode 213. House Robber II

作者: SnailTyan | 来源:发表于2019-01-30 14:31 被阅读4次

    文章作者: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/

    相关文章

      网友评论

        本文标题:Leetcode 213. House Robber II

        本文链接:https://www.haomeiwen.com/subject/sjqcsqtx.html