1-D DP: house robber, decode ways, jump game II
One-dimensional DP keeps one value per position, built from the previous one or two, as in house robber and decode ways.
Before you start: The DP recipe: state, transition, base cases, order, answer.
House robber: one cell per house
The idea
Robbing two neighbouring houses sets off the alarm. What is the most money a robber can take from this street?
Six houses already allow 21 safe plans. With 40 houses there are over 260 million, so trying them all is out.
Intuition
A shorter street: 2, 1, 1, 2. Robbing every other house (A or B) gives 3, but houses 0 and 3 give 4.
Sometimes the best plan skips two houses in a row. A fixed pattern cannot see that, but comparing totals can.
For house i there are two choices. Skip it and keep dp[i − 1], or rob it and add its money to dp[i − 2].
Robbing house i rules out house i − 1, so the best plan before it ends at i − 2. Skipping it leaves the best plan for houses 0..i − 1 unchanged.
Complexity
Each house fills one cell from two earlier cells: O(n) time. The number of safe plans grows exponentially.
The y axis is logarithmic. The plan count follows the Fibonacci numbers, growing by about 1.6 times per house.
Each cell reads only the two cells before it. Two variables, prev2 and prev1, replace the table: O(1) space.
Walking back to list the robbed houses needs the full table. For the total alone, the older cells are dead weight.
Pitfalls
Setting dp[1] to money[1] forgets house 0. For houses 7 and 2 the code returns 2 instead of 7.
With one house, writing dp[1] goes past the end. Guard the second base case with n > 1, and the first with n = 0.
Variations
House robber II puts the houses in a circle. Solve the row without the last house and the row without house 0.
Kadane's algorithm keeps the best sum ending at each index. It is 1-D DP that reads only one cell back.
Decode ways: counting with one cell per prefix
The idea
With A = 1 up to Z = 26, the digits 226 read as BBF, BZ or VF. How many readings does a long string of digits have?
A string of forty 1s has over 160 million readings. Listing them one by one is hopeless.
Intuition
The last letter uses one digit or two. So dp[i] = dp[i − 1] for the single digit plus dp[i − 2] for the pair.
Readings that end with a one-digit letter and readings that end with a two-digit letter never overlap. Their counts add.
A 0 is never a letter on its own. It only works as the second digit of 10 or 20.
Pairs from 10 to 26 are letters. A pair starting with 0, like 06, is not, and neither is 27 or more.
Complexity
Each digit fills one cell with O(1) work: O(n) time. The number of readings grows exponentially.
The y axis is logarithmic. For a string of n 1s the readings follow the Fibonacci numbers.
Each cell reads only the two cells before it. Two variables replace the table: O(1) extra space.
Pitfalls
Checking only pair ≤ 26 counts 06 as F. Require 10 ≤ pair ≤ 26, so a pair never starts with 0.
dp[0] must be 1, the one way to read nothing. With dp[0] = 0 every cell adds up zeros.
Variations
Climbing stairs with steps of 1 or 2 uses the same sum, with no digits to check.
Jump game II asks for the fewest jumps. Each jump covers a window of indices, and the next window ends at the farthest reach.
Min cost for tickets reads further back. A 7-day pass ending today jumps back to the first day it does not cover.
Code
Pseudocode
rob(money):
n ← length of money
if n = 0: return 0
dp ← array of n zeros
dp[0] ← money[0]
if n > 1: dp[1] ← max(money[0], money[1])
for i ← 2 to n - 1
dp[i] ← max(dp[i - 1], dp[i - 2] + money[i])
return dp[n - 1]
Python
def rob(money):
n = len(money)
if n == 0:
return 0
dp = [0] * n
dp[0] = money[0]
if n > 1:
dp[1] = max(money[0], money[1])
for i in range(2, n):
dp[i] = max(dp[i - 1], dp[i - 2] + money[i])
return dp[n - 1]
JavaScript
function rob(money) {
const n = money.length;
if (n === 0) return 0;
const dp = new Array(n).fill(0);
dp[0] = money[0];
if (n > 1) dp[1] = Math.max(money[0], money[1]);
for (let i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + money[i]);
}
return dp[n - 1];
}
Java
static int rob(int[] money) {
int n = money.length;
if (n == 0) return 0;
int[] dp = new int[n];
dp[0] = money[0];
if (n > 1) dp[1] = Math.max(money[0], money[1]);
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + money[i]);
}
return dp[n - 1];
}
Practice problems (7)
Pick the house robber rule Warm-up
dp[i] is the most money from houses 0..i when two neighbours cannot both be robbed. Which rule fills dp[i]?
Fill the house robber table Warm-up
Follow the house robber table for the houses 1, 2, 3, 1. Answer each question before the step plays.
House robber Standard
nums[i] is the money in house i of a street. Robbing two neighbouring houses on the same night sets off the alarm.
Return the most money you can rob without robbing two neighbours.
Decode ways Standard
Letters are encoded as numbers: A = 1, B = 2, up to Z = 26. Given a string s of digits, return how many ways it can be decoded back into letters.
A 0 cannot stand alone, and a two-digit group may not start with 0. So 06 is not a valid letter.
Jump game II Standard
You start at index 0 of nums. From index i you may jump forward by any length from 1 to nums[i].
Return the fewest jumps that reach the last index. The input always allows reaching it.
Minimum cost for tickets Standard
You travel on the days listed in days (sorted, between 1 and 365). Passes come in three kinds: 1 day for costs[0], 7 days for costs[1] and 30 days for costs[2]. A pass bought on day d covers d and the days after it, up to its length.
Return the lowest total cost that covers every travel day.
House robber II: houses in a circle Challenge
The houses now stand in a circle: house 0 and the last house are neighbours. nums[i] is the money in house i, and robbing two neighbours sets off the alarm.
Return the most money you can rob.
Related topics
Next on the path: Kadane's algorithm and maximum subarray