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.
===================================================================================================================================
这道题目的大意是:一个小偷要去一条直线街道偷东西,每间房子都有一定数量的金钱,但小偷不能偷任意相连的两间房子的金钱,不然就会触发警报系统。求小偷在不触发警报系统情况下能偷到的最大金额。
这个题目是一个简单的DP问题。用dp[i]表示从0到i房子中能偷到的最大金额,则当i>=2时,dp[i] = max ( dp[i-1] , dp[i-2] + nums[i] ) 。
附上代码:
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size() ;
if ( n == 0 )
return 0 ;
if ( n == 1 )
return nums[0] ;
int dp[n] = {0} ;
dp[0] = nums[0] ;
dp[1] = max ( nums[0] , nums[1] ) ;
for ( int i = 2 ; i < n ; i ++ )
dp[i] = max ( dp[i-1] , dp[i-2] + nums[i] ) ;
return dp[n-1] ;
}
};