C++ solution for house robber


  • 0
    G
    class Solution{
    public:
        int rob(vector<int> &nums){
            vector<int> vec(nums.size(),0);
            if(nums.size()==0)return 0;
            if(nums.size()==1)return nums[0];
            if(nums.size()==2)return max(nums[0],nums[1]);
            vec[0]=nums[0];
            vec[1]=max(nums[0],nums[1]);
            vec[2]=max(nums[0]+nums[2],nums[1]);
            for(int i=3;i<nums.size();i++){
                vec[i]=max(nums[i]+vec[i-3],max(nums[i]+vec[i-2],vec[i-1]));
            }
            return vec[nums.size()-1];
        }
    };

Log in to reply
 

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