[LeetCode] House Robber 求数组中元素两两不相邻的子序列最大和
来源:互联网 发布:python字典转化 编辑:程序博客网 时间:2024/04/29 19:43
声明:原题目转载自LeetCode,解答部分为原创
Problem :
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.
Solution:
思路:按照题意,给定一个数组array[ ],要求的是满足“元素两两不相邻”的子序列的最大和。假定函数f(k)代表以第k个元素array[k]结尾的满足该条件的子序列的最大和。
我们可以很容易得出一个结论,目标子序列中两个相邻元素在原数组array[ ]中的位置要么间隔1位,要么间隔两位。因为当间隔3位时,肯定可以将中间位加到子序列中,从而获得更大和(间隔3位以上同理)。可以得出,状态转换方程为
f(k)= array[ k ] + max( f(k - 1), f(k - 2));
穷举所有的 f(k),其最大值即为目标子序列的最大和。
代码如下:
class Solution {public: int rob(vector<int>& nums) { if(nums.size() == 0) return 0; if(nums.size() == 1) return nums[0]; if(nums.size() == 2) return max(nums[0], nums[1]); if(nums.size() == 3) return max(nums[0] + nums[2], nums[1]); vector<int> max_money(nums.size()); max_money[0] = nums[0]; max_money[1] = nums[1]; max_money[2] = max(nums[0] + nums[2], nums[1]); int result = max( max(max_money[0], max_money[1]), max_money[2] ); for(int i = 3; i < nums.size(); i ++) { max_money[i] = nums[i] + max(max_money[i - 2], max_money[i - 3]); result = max(result, max_money[i]); } return result; }};
阅读全文
0 0
- [LeetCode] House Robber 求数组中元素两两不相邻的子序列最大和
- [LeetCode] House Robber II 求循环数组中元素两两不相邻的子序列最大和
- House Robber I - 由数组中不相邻元素组成的子数组,使其和最大
- House Robber 非负数组,相邻不能相加,求最大的和是多少(动态规划)
- LeetCode (20) house robber (数组不相邻元素最大值)
- 求一个数组中最大的相邻元素之和
- 元素互不相邻的最大和子数组
- 动态规划求不相邻的最大子数组和
- 动态规划求不相邻的最大子数组和
- 动态规划求不相邻的最大子数组和
- 求不相邻的最大子数组和
- 求数组的最大子序列和
- 求数组最大子序列的和
- House Robber:在不取相邻元素的情况下对数组求和
- 数组中不相邻元素的最大和
- 找出数组中任何相邻子向量的最大和
- LeetCode 198. House Robber(必须不连续数组的最大和)
- 不相邻的最大子数组和
- 递归算法,感悟
- 设计模式学习:策略模式
- Log4j2 简明教程
- 计算机网络各层协议
- 操作系统Unix、Windows、Mac OS、Linux的故事
- [LeetCode] House Robber 求数组中元素两两不相邻的子序列最大和
- 8.Hibernate总结以及在面试中的一些问题.
- 动态代理之JDK
- java敏感词过滤
- 简单学生选课系统之课程基本信息
- Unity Shader之Stencil Buffer
- ini_set ( )—用来设置php.ini的各种配置值
- bam/sam 数据格式的介绍 (一)
- IOS-禁用右滑返回的两种方式