House Robber in Java: Explanation & Practice

Maximum money without robbing adjacent houses

Problem summary

Given an array of house values, find maximum money you can rob without robbing two adjacent houses. Classic DP with no-consecutive constraint.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {2, 7, 9, 3, 1};
        
        // At each house: rob it + dp[i-2], or skip it (dp[i-1])
        // dp[i] = max(nums[i] + dp[i-2], dp[i-1])
        // Print: Max money: 12
    }
}

Expected output and test cases

  • [2,7,9,3,1] → rob 2,9,1
    Max money: 12
  • [1,2,3,1] → rob 1,3
    Max money: 4
  • [2,1,1,2] → rob 2,2 = 4? No: 2+2=4, or 7
    Max money: 7

Hints

  1. For each house, decide: rob or skip
  2. If rob: add value + best from 2 houses back
  3. If skip: take best from previous house
  4. dp[i] = max(nums[i] + dp[i-2], dp[i-1])

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler