LeetCode (20) house robber (maximum number of elements not adjacent to the array), leetcoderobber
Description
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.
The requirements of this question can be summarized into the largest sum of elements not adjacent to the array. This question can be answered based on the idea of dynamic planning.
For the array num from 1... The largest of n and f (n) may have the following two cases (note that for convenience, assume that the starting element of the array is 1 ):
- F (n) = f (n-2) + num [n];
- F (n) = f (n-1 );
F (n) is the maximum value of the preceding two values. Of course, this question can be processed using recursive ideas, but this will carry out repeated operations (This question is actually similar to the Fibonacci series). Therefore, the previous and backward processing is more efficient, here you only need to save the values of f (n-1) and f (n-2.
The Code is as follows:
class Solution {public: int rob(vector<int> &num) { int size = num.size(); if(size == 0) return 0; if(size == 1) return num[0]; if(size == 2) return max(num[0], num[1]); int n1 = num[0]; int n2 = num[0] > num[1] ? num[0] : num[1]; for(int i = 2; i != num.size(); ++i) { int n = n1 + num[i]; int n3 = n > n2 ? n : n2; n1 = n2; n2 = n3; } int r = max(n1, n2); return r; }};