O(n) time, O(1) space, very simple Java code


  • 0
    Y
    public class Solution {
        public int rob(int[] nums) {
            //corner case
            if(nums.length==0) {
                return 0;
            }
            else if(nums.length == 1) {
                return nums[0];
            }
          
            //dynamic programming
            int first = 0;
            int second = nums[0];
            for(int i = 1; i < nums.length; i++) {
                if(nums[i]+first >= second) {
                    int tmp = second;
                    second = nums[i]+first;
                    first = tmp;
                }
                else{
                    first = second;
                }
            }
            return second;
        }
    }
    

Log in to reply
 

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