← Dynamic Programming

House Robber

Easy
Python
def rob(nums):
    a,b=0,0
    for n in nums: a,b=b,max(b,a+n)
    return b
Java
public int rob(int[] nums){
    int a=0,b=0;
    for(int n:nums){int t=Math.max(b,a+n);a=b;b=t;}
    return b;
}

Key Insight

Space-optimized. Simultaneous swap vs temp.

Python → Java Differences

  • Simultaneous swap vs temp
  • max() vs Math.max()
  • Space-optimized DP identical
Python
def rob(nums):
    a,b=0,0
    for n in nums: a,b=b,max(b,a+n)
    return b
Java
public int rob(int[] nums){
    int a=0,b=0;
    for(int n:nums){int t=Math.max(b,a+n);a=b;b=t;}
    return b;
}

Algorithm Steps

1. Track two previous values
2. Rob current or skip