Dynamic Programming Simplified - Part 2

Solving LeetCode House Robber problem

Problem statement

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Goal: Calculate the maximum money you can rob without robbing two adjacent houses.

Problem breakdown

Unlike Fibonacci, this problem's recursive pattern isn't immediately obvious. We'll use the same technique: start with the simplest cases.

Base cases:

Building the pattern:

General pattern: f(n) = max(nums[n] + f(n-2), f(n-1))

When adding a new house, you have two choices: 1. Rob it: Get its money + optimal solution excluding the previous house 2. Skip it: Keep the optimal solution including the previous house

Take whichever gives more money.

Scala Implementation

Let's implement this using pure functional tail recursive style:

// file: house-robber.sc
def rob(houses: Array[Int]): Int =
  def go(i: Int, prevMax: Int, currMax: Int): Int =
    if i >= houses.length then currMax
    else
      val newMax = math.max(houses(i) + prevMax, currMax)
      go(i + 1, currMax, newMax)
  
  if houses.isEmpty then 0
  else go(0, 0, 0)

// Test cases
val houses1 = Array(2, 7, 9, 3, 1)
val houses2 = Array(2, 1, 1, 2)
val houses3 = Array(5)

println(rob(houses1)) // output: 12 (rob houses with 2, 9, 1)
println(rob(houses2)) // output: 4 (rob houses with 2, 2)
println(rob(houses3)) // output: 5 (rob the only house)

How it works:

The time complexity is O(n) and space complexity is O(1)