Original title link : https://leetcode.com/problems/house-robber/
Test Instructions Description :
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.
Exercises
The goal of this problem is to select a subset from an array, so that the maximum and constraint is that the selected subset cannot be contiguous in the original array. It is obvious that this kind of optimization is usually to rely on the dynamic planning.
The specific state transfer can be expressed as, when the number of the first, there are two choices, select or not, assuming that if selected, then the optimal value is DP1, not selected, the optimal value is dp0, then it is obvious
DP0 = max (DP1,DP0), which is the larger value in the best value of the previous or not selected;
DP1 = Dp0+val[i], note that the dp0 here is not the dp0 of the previous row, but the optimal value in the previous state, because only the last one is selected.
It's easy to find the code.
The specific code is as follows:
1 Public classSolution {2 Public intRobint[] num) {3 intdp0 = 0;4 intDP1 = 0;5 for(inti = 0; i < num.length; i++) {6 intTMP =dp0;7Dp0 =Math.max (DP1, dp0);8DP1 = tmp+Num[i];9 }Ten returnMath.max (dp0, DP1); One } A}
[Leetcode] House robber