House Robber II( Simple Java Solution- O(n))


  • 0
    J

    class Solution {
    public int rob(int[] nums) {

        int len = nums.length;
    
        if(nums == null || len == 0) return 0;
        if(len == 1) return nums[0];
        
        int[] profit = new int[len];
        int max = 0;
        
        for(int i = 0; i < len-1; i++) {
            if(i == 0) profit[i] = nums[i];
            else if(i == 1) profit[i] = Math.max(nums[i-1], nums[i]);
            else{
                profit[i] = Math.max(profit[i-2] + nums[i], profit[i-1]);
            }
            max = Math.max(max, profit[i]);
        }
        
         for(int i = 1; i < len; i++) {
            if(i == 1) profit[i] = nums[i];
            else if(i == 2) profit[i] = Math.max(nums[i-1], nums[i]);
            else{
                profit[i] = Math.max(profit[i-2] + nums[i], profit[i-1]);
            }
            max = Math.max(max, profit[i]);
        }
        
        return max;   
    }
    

    }


Log in to reply
 

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