码迷,mamicode.com
首页 > 其他好文 > 详细

198. House Robber

时间:2017-10-18 18:27:15      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:ace   can   []   [1]   alert   pre   you   rmi   security   

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         if (nums == null || nums.length == 0)
 3             return 0;
 4         int len = nums.length;
 5         if (len == 1)
 6             return nums[0];
 7         if (len == 2) {
 8             return Math.max(nums[0],nums[1]);
 9         }
10         int[] rt = new int[len];
11         rt[0] = nums[0];
12         rt[1] = Math.max(nums[0],nums[1]);;
13         for (int i = 2; i < len; i++) {
14             rt[i] = Math.max(rt[i - 1], rt[i - 2] + nums[i]);
15         }
16         return  Math.max(rt[len - 1],rt[len - 2]);      
17     }

 

198. House Robber

标签:ace   can   []   [1]   alert   pre   you   rmi   security   

原文地址:http://www.cnblogs.com/wzj4858/p/7687867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!