Java solution 0ms O(n) in time and O(n) in space

  • 0

    public int rob(int[] nums) {
    int length = nums.length;
    if(nums==null || nums.length==0) return 0;
    if(nums.length==1)return nums[0];
    return nums[0]>nums[1] ? nums[0] : nums[1];
    if(nums.length==3){return (nums[1]>(nums[0]+nums[2]))?nums[1]:(nums[0]+nums[2]);}
    int[] max = new int[nums.length];
    max[0] = nums[0];
    max[1] = Integer.max(nums[0],nums[1]);
    for(int i=2;i<nums.length;i++){
    max[i] = ((nums[i]+max[i-2]) >max[i-1])?(nums[i]+max[i-2]):max[i-1];
    return max[nums.length-1];

Log in to reply

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