O(1) space O(n) c++ solution


  • 0
    P
    class Solution {
    public:
        int rob(vector<int> &a) {
            int n = a.size();
            if (n==0) return 0;
            if (n==1) return a[0];
            if (n==2) return max(a[0],a[1]);
            int n1 = a[0];
            int n2 = a[1];
            int maxRob = INT_MIN;
            for (int i = 2; i < n; ++i) {
                maxRob = max(n1+a[i],n2);
                n1 = max(n1,n2);
                n2 = maxRob;
            }
            return maxRob;
        }
    };

Log in to reply
 

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