More clear approach than the 3 variable method - Java Solution O(N)


  • 0
    R

    The logic is you choose the maximum of

    1. current-2 + current
    2. current-1 value
     public int rob(int[] nums) {   
        int len = nums.length;
        HashMap<Integer,Integer> dp = new HashMap<>();
        dp.put(-2,0);
        dp.put(-1,0);
        int i;
        for(i = 0 ; i < len ; i++){
            dp.put( i,Math.max(dp.get(i-2)+nums[i],dp.get(i-1)) );
        }
        
        return dp.get(i-1);
    }

Log in to reply
 

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