O(n) time and space complexity. Java


  • 0
    O
    
        public int rob(int[] nums) {
            if (nums.length == 0) return 0;
            if (nums.length == 1) return nums[0];
            if (nums.length == 2) return Math.max(nums[0], nums[1]);
            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 = Math.max(memo[1], memo[2]);
            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];
                }
            }
            
            return Math.max(Math.max(memo[0], memo[1]), second);
        }
    

Log in to reply
 

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