LeetCode (20) house robber (数组不相邻元素最大值)
2015-04-22 15:48
465 查看
题目描述
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.
这道题目的要求可以归纳为数组不相邻元素的最大和。这道题目可以根据动态规划的思想去解答。
对数组num从1…n的最大和f(n)可能有以下两种情况(注意这里为了说明方便,假设数组的起始元素为1):
f(n) = f(n-2) + num
;
f(n) = f(n-1);
f(n)取以上两个值的最大值。当然本题可以使用递归的思路去处理,但是这样会进行多次重复的运算(本题其实类似于斐波那契数列),因此,从前向后的处理更有效率,这里只需要保存f(n-1)和f(n-2)的值即可。
代码如下:
class Solution { public: int rob(vector<int> &num) { int size = num.size(); if(size == 0) return 0; if(size == 1) return num[0]; if(size == 2) return max(num[0], num[1]); int n1 = num[0]; int n2 = num[0] > num[1] ? num[0] : num[1]; for(int i = 2; i != num.size(); ++i) { int n = n1 + num[i]; int n3 = n > n2 ? n : n2; n1 = n2; n2 = n3; } int r = max(n1, n2); return r; } };
相关文章推荐
- [LeetCode] House Robber II 求循环数组中元素两两不相邻的子序列最大和
- LeetCode—House Robber 寻找数组不相邻组合最大值DP
- House Robber I - 由数组中不相邻元素组成的子数组,使其和最大
- [LeetCode] House Robber 求数组中元素两两不相邻的子序列最大和
- House Robber III:打家劫舍 在二叉树结构中取非相邻元素求和取最大
- House Robber:在不取相邻元素的情况下对数组求和
- House Robber II:打家劫舍 取非相邻元素求和最大,且认为第一个元素与最后一个元素相邻
- LeetCode-198. House Robber (JAVA)寻找数组不相邻组合最大值DP
- Leetcode421. 找出数组中两个元素异或的最大值
- 求2维数组相邻元素的和的最大值
- 给一个整数数组,有正有负。找出数组最大和,条件是使用的元素不能有相邻
- 每天一道LeetCode-----在给定数组中找到一个子数组,使得这个子数组的元素乘积最大
- 算法习题45:对于一个整数矩阵,存在一种运算,对矩阵中任意元素加一时,需要其相邻(上下左右)某一个元素也加一;;;一个整数数组,长度为n,将其分为m份,使各份的和相等,求m的最大值
- leetcode_198. House Robber 抢劫不相邻的房子,使得抢到的金钱数目最大, 动态规划
- 求一个数组中最大的相邻元素之和
- Ruby实现求数组内相邻元素的最大和-《编程珠玑》问题求解
- 数组最大相邻元素之和
- leetcode 164. Maximum Gap 相邻元素的最大间隔 + 一个很好的桶排序示范
- 求数组相邻元素差值的最大值快速算法(C++版)
- LeetCode-628:Maximum Product of Three Numbers (数组三元素最大乘积)