## Sunday, July 23, 2017

### [Leetcode] House Robber, Solution

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.

[Thoughts]

rob[i] = no_rob[i-1] + house[i];
no_rob[i] = max( rob[i-1], no_rob[i-1]);

2             1              1               2
rob           2             1              3               4
no_rob      0              2             2               3

[Code]

``````1:    int rob(vector<int>& nums) {
2:      int len = nums.size();
3:
4:      if(len == 0) return 0;
5:
6:      if(len == 1) return nums[0];
7:
8:      int rob=0, no_rob=0;
9:      for(int i =0; i< len; i++) {
10:        int new_rob = no_rob + nums[i];
11:        no_rob = max(rob, no_rob);
12:        rob = new_rob;
13:      }
14:
15:      return max(rob, no_rob);
16:    }
``````