198. House Robber

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.

题目含义:给定一个整数数组Arr,求解数组中连续的不相邻元素的和的最大值。例如:对于数组中的元素A1,A2,A3,A4,则需要判断A1+A3,A1+A4,A2+A4中的最大值即为所求。

思路:对于n个数的数组,如果要求得其连续不相邻元素的最大值,那么我们只需求得n-1个数的最大值,以及求得n-2个数的最大值即可,这样就形成了求解该问题的子问题的最大值问题,所以很容易考虑出递推关系,假设数组为Arr[],n个数的数组对应的不相邻连续元素的最大值用函数f(n)表示,则有f(n) = max{f(n-1), f(n-2)+A[n-1]},其中n>=2,f(n)也称为递推关系。其中f(n-1)为n-1个元素的最大值,f(n-2)+Arr[n-1]为n-2个元素的最大值加上数组第n个元素的值,因为要求元素不能相邻,所以会跳过第n-1个元素,这个应该很好理解。

 1     public int rob(int[] nums) {
 2 //        我们维护一个一位数组dp,其中dp[i]表示到i位置时不相邻数能形成的最大和
 3         if (nums.length == 0) return 0;
 4         if (nums.length ==1) return nums[0];
 5         int[]dp = new int[nums.length];
 6         dp[0] = nums[0];
 7         dp[1] = Math.max(nums[0],nums[1]);
 8         for (int i=2;i<nums.length;i++)
 9         {
10             dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]);
11         }
12         return dp[dp.length-1];
13 
14 //        还有一种解法,核心思想还是用DP,分别维护两个变量a和b,然后按奇偶分别来更新a和b,这样就可以保证组成最大和的数字不相邻,
15 //        int a = 0, b = 0;
16 //        for (int i = 0; i < nums.length; ++i) {
17 //            if (i % 2 == 0) {
18 //                a += nums[i];
19 //                a = Math.max(a, b);
20 //            } else {
21 //                b += nums[i];
22 //                b = Math.max(a, b);
23 //            }
24 //        }
25 //        return Math.max(a, b);   
26     }
原文地址:https://www.cnblogs.com/wzj4858/p/7687867.html