Simple Java Solution


  • 0
    Z
    public class Solution {
        public int rob(int[] nums) {
            if(nums == null || nums.length == 0){
                return 0;
            }
            int maxOdd = 0;
            int maxEven = nums[0];
            for (int i = 1; i < nums.length-1; i++) {
                if(i % 2 == 0){
                    maxEven = Math.max(maxEven+nums[i],maxOdd);
                }else {
                    maxOdd = Math.max(maxOdd+nums[i], maxEven);
                }
            }
    
            int max1 = Math.max(maxEven, maxOdd);
            maxEven = maxOdd = 0;
    
            for (int i = 1; i < nums.length; i++) {
                if(i % 2 == 0){
                    maxEven = Math.max(maxEven+nums[i],maxOdd);
                }else {
                    maxOdd = Math.max(maxOdd+nums[i], maxEven);
                }
            }
    
            int max2  = Math.max(maxEven, maxOdd);
            return Math.max(max1, max2);
        }
    }
    

Log in to reply
 

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