2015年10月24日星期六

Leetcode 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 1:  Use DP to record of current max value of rob this one and noRob this one 
 public class Solution {  
   public int rob(int[] nums) {  
     int n=nums.length;  
     if (n==0) return 0;  
     int rob=0;  
     int notRob=0;  
     for (int i=0; i<n; i++) {  
       if (i==0) {  
         rob=nums[i];  
         notRob=0;  
       }  
       else {  
         int temp=Math.max(rob,notRob);  
         rob=notRob+nums[i];  
         notRob=temp;  
       }  
     }  
     return Math.max(rob,notRob);  
   }  
 }  

没有评论:

发表评论