C++ solution, space O(n)


  • 0
    J
        int rob(vector<int>& nums) {
            if(nums.empty()) return 0;
            int n=nums.size();
            vector<int> Max(n);
            Max[0]=nums[0];
            if(nums[1]>nums[0]) Max[1]= nums[1];
            else Max[1]=nums[0];
            for(int i=2;i<n;i++){
                Max[i] = max(Max[i-2]+nums[i],Max[i-1]);
            }
            return Max[n-1];
        }
    

Log in to reply
 

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