Sharing my DP Solution


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

Log in to reply
 

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