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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
Dynamic planning. State transition equation: dp[i] = max (dp[i-1], dp[i-2] + num[i])
1 classSolution {2 Public:3 intRob (vector<int> &num) {4 intn =num.size ();5 if(n = =0)return 0;6vector<int> DP (N,0);7dp[0] = num[0];8 for(inti =1; I < n; ++i) {9 if(I <2) Dp[i] = max (dp[i-1], num[i]);Ten ElseDp[i] = max (dp[i-1], dp[i-2] +num[i]); One } A returndp[n-1]; - } -};
or dynamic rules, respectively, maintain to the odd subscript when and to even subscript when the maximum and.
1 classSolution {2 Public:3 intRob (vector<int> &num) {4 intOdd =0, even =0;5 for(inti =0; I < num.size (); ++i) {6 if(I &0x1) odd = max (odd +Num[i], even);7 Elseeven = max (even +Num[i], odd);8 }9 returnMax (odd, even);Ten } One};
[Leetcode] House robber