# [Leetcode] House robber

Source: Internet
Author: User

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

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.