码迷,mamicode.com
首页 > 其他好文 > 详细

198. House Robber

时间:2017-05-27 10:26:58      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:bing   automatic   res   ica   nal   sys   max sum   int   tor   

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: use the idea of dynamic programming. use dp[i] to represent the max sum of non-adjacent numbers till i. the formula is dp[i]=max(dp[i-2]+nums[i],dp[i-1]), the initial is dp[0]=nums[0],dp[1]=max(nums[0],nums[1]). Here we only need dp[i-2] and dp[i-1] to get dp[i], so we can use two variants dp_pre2 and dp_pre1 to replace the dp array.

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

 

])

198. House Robber

标签:bing   automatic   res   ica   nal   sys   max sum   int   tor   

原文地址:http://www.cnblogs.com/anghostcici/p/6911159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!