First, the topic
You is a professional robber planning to rob houses along a street. Each house have a certain amount of money stashed, the only constraint stopping all from robbing each of the them are that Adjac ENT houses have security system connected and it would automatically contact the police if the adjacent houses were broken Into on the same night.
Given a list of non-negative integers representing the amount of money in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.
Second, analysis
A simple dynamic plan.
F (k): The maximum amount of money to be obtained when robbing a room K
The following recurrence relationship is available:
F (0) = nums[0]f (1) = max (num[0], num[1= max (f (k 2) + nums[k], f (k1))
Third, the Code
1) More easy to understand, the interpretation of the above three formula
1 classSolution {2 Public:3 intRob (vector<int>&nums) {4 intLength =nums.size ();5 if(Length = =0)6 return 0;7vector<int> Money (length, nums[0]);8 if(Length = =1)9 returnnums[0];Ten Else { Onemoney[1] = max (nums[0], nums[1]); A for(inti =2; i < length; ++i) { -Money[i] = max (money[i-1], money[i-2] +nums[i]); - } the } - returnMoney[length-1]; - - } +};
2) optimization of the above program
1 classSolution {2 Public:3 intRob (vector<int>&nums) { 4 intn = nums.size (), pre =0, cur =0;5 for(inti =0; I < n; i++) {6 intTEMP = max (pre +nums[i], cur);7Pre =cur;8Cur =temp;9 }Ten returncur; One } A};
3) Python implementation
1 class Solution: 2 3 def Rob (Self, nums): 4 5 Last, today = 0, 06 7for in nums:last, now = Now, Max ( Last + I, now)8 9 return now
198,house robber