Easy understand, 8 lines Java O(n) solution, space O(1)


  • 0
    P
    public int rob(int[] nums) { //space O(1)
            if (nums.length == 0) return 0;
            int dp1 = 0, dp2 = nums[0];
            for (int i = 2; i <= nums.length; i++) {
                int cur = Math.max(dp1 + nums[i - 1], dp2);
                dp1 = dp2;
                dp2 = cur;
            }
            return dp2;
        }
    

Log in to reply
 

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