[LeetCode]House Robber II
来源:互联网 发布:最准的掐指算法姻缘 编辑:程序博客网 时间:2024/05/23 19:07
Question
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
本题难度Medium。
题意
房子围城圈,抢头就不能抢尾。
DP
复杂度
时间 O(N) 空间 O(1)
思路
这道题难点在于围成圈,解决关键就在于最后那个房子的判断,实际上还是换汤不换药。设到达最后那个房子状态为f[N]
,它只有两个可能:
- 抢最后那个房子,那么就不能抢第一个房子
- 不抢最后那个房子,那么
f[N]=f[N-1]
我们只要另外用一个数组n[i]
来表示不抢第一个房子的状态,结果就是max(f[N-1],n[N])
。这里同样可以使用[LeetCode]House Robber 的优化,使用2对变量即可。
代码
public class Solution { public int rob(int[] nums) { //require int N=nums.length; if(N<2)return N==0?0:nums[0]; //a1、b1是正常的,a2、b2是不抢第一个房子 int a1=nums[0],b1=Math.max(a1,nums[1]),a2=0,b2=nums[1]; //invariant for(int i=2;i<N;i++){ int tmp1=b1,tmp2=b2; b1=Math.max(a1+nums[i],b1); b2=Math.max(a2+nums[i],b2); a1=tmp1;a2=tmp2; } //ensure return Math.max(a1,b2); //注意不是max(b1,b2) }}
- LeetCode House Robber II
- [LeetCode] House Robber II
- [leetcode] House Robber II
- 【leetcode】House Robber II
- Leetcode: House Robber II
- leetcode House Robber II
- [leetcode] House Robber II
- [LeetCode]House Robber II
- leetcode--House Robber II
- leetcode House Robber II
- LeetCode House Robber II
- leetcode:House Robber II
- Leetcode: House Robber II
- House Robber II -- leetcode
- leetCode House Robber II
- [Leetcode]House Robber II
- Leetcode: House Robber II
- LeetCode House Robber II
- 如何判断Fragment是否对用户可见
- 《视觉计算理论》阅读笔记——第一章
- [PHP]date函数参数
- Android:网络层的封装(使用OkHttp)
- 设置文字滚动
- [LeetCode]House Robber II
- hackinglab.cn 注入关之二
- value目录下的尺寸定义
- Java框架--注解模式:@Repository @Service @Controller @Autowired
- 线性回归
- 这里整理了基于java平台的常用资源
- Cloudera Manager5在线安装停止在获取安装锁、不能选择安装主机、本地 parcel 错误
- CentOS 6.5 下安装 Redis 2.8.7
- 先睹为快 ▏Kubernetes 1.5有哪些你不得不知的新功能?