Python solution, 3 lines.

• Based on the recursive formula:

``````f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )
``````
``````class Solution:

def rob(self, nums):

last, now = 0, 0

for i in nums: last, now = now, max(last + i, now)

return now``````

• cool!!.......................

• This is pretty nice. But arranging the loop content with `for` on the same line isn't Pythonic...

• @qkhhly Yes, but if he fixed it he would need to change the title.

• @pisskidney hahaha

• @totolipton very cool and concise. For comparison, here's the C#, not as compact that's for sure!

``````    public int Rob(int[] nums)
{
int prev1 = 0;
int prev2 = 0;
int curr = 0;
foreach (int x in nums)
{
curr = Math.Max(x + prev2, prev1);
prev2 = prev1;
prev1 = curr;
}
return curr;
}
``````

• @jdrogin man, you code it's slightly different from this Python version, I guess you meant something like this:

``````public int Rob(int[] nums)
{
int prev1 = 0, prev2 = 0, temp = 0;

foreach (int x in nums)
{
temp = prev1;
prev1 = Math.Max(x + prev2, prev1);
prev2 = temp;
}
return prev1;
}
``````

• @totolipton
nice solution, thanks

• This post is deleted!

• Looks like a very elegant solution, but i dont quite get how it works.

since in each iteration, last is assigned the value of now, wouldn't now always be then updated as last+i, since now = last so last+i>last?
how does the solution handle the condition of not allowing to rob adjacent houses?

Thanks

• @chongkuan123 Chongkuan, please make sure you understand how the following codes works in Python:

``````last, now = now, max(last + i, now)
``````

Here is an simple example, hope this helps:

``````>>>n,m=2,3
>>>n,m=m,n
>>>n,m
>>>3,2

``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.