O(n) time O(1) space DP C++ Solution


  • 0
    int rob(vector<int>& nums) {
        if( nums.empty()) return 0;
        int ans = 0, a,b,c,d,p,q;
        for( int i=0; i<nums.size(); i++ ) {
            p = i < 2 ? 0 : b;
            q = i < 3 ? 0 : a;
            d = max(p, q) + nums[i];
            ans = max( ans, d);
            a = b; b = c; c = d;
        }
        return ans;
    }

Log in to reply
 

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