Java solution with O(1) space


  • 2
    K
    public class Solution {
        public int rob(int[] nums) {
            if(nums == null || nums.length == 0) return 0;
            int rob1 = 0, rob2 = nums[0], max = nums[0];
            for(int i = 1; i < nums.length; ++i) {
                max = Math.max(rob1+nums[i], rob2);
                rob1 = rob2;
                rob2 = max;
            }
            return max;
        }
    }
    

Log in to reply
 

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