O(1) space DP in Java


  • 2
    N
    public int rob(int[] nums) {
            
            if(nums == null || nums.length == 0) return 0;
            
            int max = nums[0];
            int pre = max;
            
            for(int i = 1; i < nums.length; i++){
                if(i == 1){
                    max = Math.max(max, nums[i]);
                }else{
                    int preMax = max;
                    max = Math.max(max, pre+nums[i]);
                    pre = preMax;
                }
            }
            
            return max;
        }

  • 0
    L

    if you set pre = 0, then you needn't the case of if(i == 1){max = Math.max(max, nums[i]); }


Log in to reply
 

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