Thursday, September 7, 2017

198. House Robber

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.

Solution:
State machine. 
For each house, there are only two possibilities, either we rob the house or not.  If we define the max money we robbed till house i as robbed[i] if we rob the current house and unRobbed[i] if we don't rob the current house. 
Apparently, robbed[i] = num[i] + unRobbed[i-1] and unRobbed[i] = Math.max(unRobbed[i-1], robbed[i-1]) 
We can calculate along the house and get robbed[n] and unRobbed[n]
The final result should be larger one between these two.
Time complexity O(n).
Since we only need previous state in order to calculate the current state, we can use two variable to track previous status so space complexity should be O(1).

 public int rob(int[] nums) {  
     int robbed=0;  
     int notRobbed=0;  
     for(int i=0;i<nums.length;i++){  
       int temp=notRobbed;  
       notRobbed=Math.max(robbed,notRobbed);  
       robbed=nums[i]+temp;  
     }  
     return Math.max(robbed,notRobbed);      
   }  

No comments:

Post a Comment