c++ solution


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

Log in to reply
 

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