Clean JAVA AC solution


  • 0
    W
        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]);
            
            return Math.max(robInRange(nums, 0, nums.length - 2), robInRange(nums, 1, nums.length - 1));
        }
        
        private int robInRange(int[] nums, int start, int end) {
            int prev = 0;
            int prevOfPrev = 0;
            for (int i = start; i <= end; i++) {
                int rob = nums[i] + prevOfPrev;
                int noRob = Math.max(prev, prevOfPrev);
                prevOfPrev = prev;
                prev = Math.max(rob, noRob);
            }
            return prev;
        }
    

Log in to reply
 

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