Accepted Java solution.


  • 1
    O
    
        public int rob(int[] nums) {
            if (nums.length == 0) return 0;
            if (nums.length == 1) return nums[0];
            int[] memo = new int[nums.length];
            int i = 0;
            for(i = 0; i < nums.length; i++) {
                memo[i] = nums[i];
            }
            for (i = nums.length-3; i >= 0; i--) {
                if (i+3 < nums.length) {
                    memo[i] += Math.max(memo[i+2], memo[i+3]);
                } else {
                    memo[i] += memo[i+2];
                }
            }
            int second = memo[1];
            for(i = 0; i < nums.length; i++) {
                memo[i] = nums[i];
            }
            for (i = nums.length-4; i >= 0; i--) {
                if (i+3 < nums.length-1) {
                    memo[i] += Math.max(memo[i+2], memo[i+3]);
                } else {
                    memo[i] += memo[i+2];
                }
            }
            second = Math.max(memo[0], second);
            for(i = 0; i < nums.length; i++) {
                memo[i] = nums[i];
            }
            for (i = 4; i <= nums.length-1; i++) {
                if (i-3 > 0) {
                    memo[i] += Math.max(memo[i-2], memo[i-3]);
                } else {
                    memo[i] += memo[i-2];
                }
            }
            
            return Math.max(memo[nums.length-1], second);
        }
    

Log in to reply
 

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