A short C++ solution, linear time, constant space


  • 0
    W

    class Solution {

    public:
    int rob(vector<int>& nums) {

        int size = nums.size();
        int sums[] = {0,0,0};
        for(int i=3; i<size+3; i++){
            sums[i%3] = max(max(sums[(i-2+3)%3],sums[(i-3+3)%3])+nums[i-3],sums[(i-1)%3]);
        }
        return sums[(size-1)%3];
    }
    

    };


Log in to reply
 

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