My java solution ~


  • 0
    Y
    public class Solution {
    public int rob(int[] nums) {
        if(nums.length == 0 || nums == null) return 0;
        int max = 0;
        if(nums.length <= 3) {
            for(int i = 0; i < nums.length; i++) {
                max = Math.max(max, nums[i]);
            }
            return max;
        }
        // robber nums[0] 
        int lastT = nums[2];
        int lastF = 0;
        int curT = nums[2],curF = 0;
        for(int i = 3; i < nums.length - 1; i++) {
            curT = lastF + nums[i];
            curF = Math.max(lastT, lastF);
            lastT = curT;
            lastF = curF;
        }
        int sum1 = Math.max(curT, curF) +nums[0];
        
        // no robber nums[0]
        lastT = nums[1];
        lastF = 0;
        curT = nums[1];
        curF = 0;
        for(int i = 2; i < nums.length; i++) {
            curT = lastF + nums[i];
            curF = Math.max(lastT, lastF);
            lastT = curT;
            lastF = curF;
        }
        int sum2 = Math.max(curT, curF);
        
        return Math.max(sum1,sum2);
    }
    

    }


Log in to reply
 

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