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 bro Ken 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.
Thinking of solving problems
Dynamic planning
State transfer equation: F[i] =max (f[i-1], f[i-2]+c[i])
F[i] Represents the greatest wealth obtained when entering the i+1 room.
To save space, just use three variables prepre, pre, cur.
Implementation Code 1
//runtime:2msclassSolution { Public:intRob vector<int>& Nums) {intLen = Nums.size ();if(len = =0)return 0;if(len = =1)returnnums[0];if(len = =2)returnMax (nums[0], nums[1]);intPrepre = nums[0];intPre = MAX (nums[0], nums[1]);intCur for(inti =2; i < Len; i++) {cur = max (pre, Prepre + nums[i]); Prepre = pre; Pre = cur; }returnCur }};
Implementation Code 2
# runtime:76ms class solution: # @param {integer[]} nums # @return {integer} def Rob(self, nums):size = Len (nums)ifSize = =0:return 0 elifSize = =1:returnnums[0]elifSize = =2:returnMax (nums[0], nums[1]) Prepre = nums[0] Pre = MAX (nums[0], nums[1]) forIinchRange2, size): cur = max (pre, Prepre + nums[i]) Prepre = Pre Pre = curreturnCur
[Leetcode] House robber