3 ms C++ solution, O(1) Space


  • 0
    B
    class Solution {
    public:
        int rob(vector<int> &num) {
            int N = num.size();
            if(N < 1)return 0;
            if(N == 1)return num[0];
            int pre = num[0], cur = num[1]>pre?num[1]:pre, next = 0;
            for(int i = 2; i < N; i ++)
            {
                next = pre + num[i];
                if(cur > next)next = cur;
                pre = cur;
                cur = next;
            }
            return cur;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.