House Robber DP Solution Java, 0ms


  • 2
    V
        public int rob(int[] nums) {
            int n = nums.length;
            if( n == 0 ) return 0;
            else if ( n == 1 ) return nums[0];
            else if ( n < 3 ) return Math.max(nums[0],nums[1]);
            int[] money = new int[n];
            money[0] = nums[0]; //maximum sum at house #1
            money[1] = Math.max(money[0],nums[1]); //maximum sum at house #2
            for(int i = 2; i < n; i++) {
                /* Do I rob the current house, or skip it */
                money[i] = Math.max((nums[i]+money[i-2]),money[i-1]);
            }
            return money[n-1];
        }
    

Log in to reply
 

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