<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " >you is a professional robber planning to rob houses along a street. Each house had a certain amount of money stashed (hidden), </span>
The only constraint stopping are robbing each of them are that adjacent houses has security system connected and it W Ill automatically contact the police if
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.
Hide tags:dynamic Programming
Problem Solving Ideas:
Idea One: a[i][0] indicates that the first time no robbery, A[i][1] said I was robbed, that is a[i+1][0] = max (a[i][0], a[i][1]). So Rob's current house, just wait.
A[I+1][1] = a[i][0]+money[i+1] In the last +money[i+1 without Rob]. In fact, only two variables are required to save the result, and no two-dimensional array is required.
Idea two: Find a recursive relationship: maxv[i] = max (Maxv[i-2]+num[i], maxv[i-1])
Code One:
/** * This is a DP (Dynamic programming: Dynamics Planning) Problem * A[i][0] indicates that the first time no robbery, a[i][1] means I was robbed * ie a[i+1][0] = max (a[i][0], a[i][1]). So Rob's current house, * can only equal the last time without Rob +money[i+1], then a[i+1][1] = a[i][0]+money[i+1] * Actually only need two variables to save the result, do not need to use a two-dimensional array */public static int Rob (int[] nums) {int norobcurhouse=0;//indicates that the total amount of the current house has not been robbed int robcurhouse=0;//means the total amount of the current house has been robbed for (int i = 0; i < nums . length; i++) {//Set intermediate variable, temporarily store int temp=norobcurhouse,//No current houses selected, then it equals last selected or not selected maximum Norobcurhouse=math.max (Norobcurhouse, Robcurhouse);//Select the current houses, the value can only be equal to the last not selected + the current houses moneyrobcurhouse=temp+nums[i];} Return Math.max (Norobcurhouse, robcurhouse);}
Code Two:
/** * Recursive relationship for maxv[i] = max (Maxv[i-2]+num[i], maxv[i-1]) */public static int rob1 (int[] nums) {int n=nums.length;if (n==0 ) {return 0;} else if (n==1) {return nums[0];} Else{int []maxv=new Int[n];maxv[0]=nums[0];maxv[1]=math.max (Nums[0], nums[1]); for (int i = 2; i < n; i++) {Maxv[i]=math . Max (Maxv[i-2]+nums[i], maxv[i-1]);} return maxv[n-1];}}
leetcode--198 House robber (looking for an array of nonadjacent combined maximums-dynamic programming issues)