Java Solution 2 pass


  • 0
    E
    public class Solution {
        public int rob(int[] nums) {
          if(nums == null || nums.length == 0) return 0;
          if(nums.length == 1) return nums[0];
          
          return Math.max(profit(nums, 0, nums.length - 1), profit(nums, 1, nums.length));
        }
        
            public int profit(int arr[], int start, int end){
                int even = 0, odd = 0;
                for(int i = start; i < end; i++){
                    if(i % 2 == 0)
                      odd = Math.max(odd + arr[i], even);
                    else
                      even = Math.max(even + arr[i], odd);
                }
                return Math.max(odd, even);
            }
        }

Log in to reply
 

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