This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

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 system connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight **without alerting the police**.

**Credits:**

Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

b'

\n## Solution

\n

\n#### Approach #1 (Dynamic Programming) [Accepted]

\n\n

'
\n\n

\n\n

**Algorithm**

It could be overwhelming thinking of all possibilities on which houses to rob.

\nA natural way to approach this problem is to work on the simplest case first.

\nLet us denote that:

\n\n\n\n

f(k) = Largest amount that you can rob from the firstkhouses.

\nA_{i}= Amount of money at the i^{th}house.

Let us look at the case `n = 1`

, clearly *f*(1) = A_{1}.

Now, let us look at `n = 2`

, which *f*(2) = max(A_{1}, A_{2}).

For `n = 3`

, you have basically the following two options:

- \n
- \n
Rob the third house, and add its amount to the first house\'s amount.

\n \n - \n
Do not rob the third house, and stick with the maximum amount of the first two houses.

\n \n

Clearly, you would want to choose the larger of the two options at each step.

\nTherefore, we could summarize the formula as following:

\n\n\n\n

f(k) = max(f(k\xe2\x80\x93 2) + A_{k},f(k\xe2\x80\x93 1))

We choose the base case as *f*(\xe2\x80\x931) = *f*(0) = 0, which will greatly simplify our code as you can see.

The answer will be calculated as *f*(*n*). We could use an array to store and calculate the result, but since at each step you only need the previous two maximum values, two variables are suffice.

public int rob(int[] num) {\n int prevMax = 0;\n int currMax = 0;\n for (int x : num) {\n int temp = currMax;\n currMax = Math.max(prevMax + x, currMax);\n prevMax = temp;\n }\n return currMax;\n}\n

**Complexity analysis**

- \n
- \n
Time complexity : .\nAssume that is the number of houses, the time complexity is .

\n \n - \n
Space complexity : .

\n \n