House Robber

35 min · rob()

Every house offers cash, but each choice can lock the next door.

The array nums lists the amount available in each house along one street. You can't rob two adjacent houses, meaning houses whose indices differ by exactly 1. Return the largest total you can collect without choosing an adjacent pair.

You may skip any house. A house may contain 0, and each amount can be used at most once.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

Hints

Two choices at each door

At house i, either skip it and keep the best total through i - 1, or take it and add its cash to the best total through i - 2.

Name the smaller problem

Let best[i] mean the best total from the first i houses. Write the two choices using that state before you write any loop.

The street behind you

The next decision reads only the best totals from one and two houses back. Those two values can roll forward with you.

Follow-up

Can you also reconstruct which house indices produce the maximum total? What extra information would you keep?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  2,
  3,
  1
]
Expected
4
Why
houses 0 and 2 contribute 1 + 3

Example 2

ready
Input
nums = [
  2,
  7,
  9,
  3,
  1
]
Expected
12
Why
houses 0, 2, and 4 contribute 2 + 9 + 1

Example 3

ready
Input
nums = [
  2,
  1,
  1,
  2
]
Expected
4
Why
the two end houses aren't adjacent

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite