House Robber II
2015-08-19 15:03
351 查看
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.
思路:与House Robber(/article/8667869.html)的区别是,整个数组的第一个数字和第二个数字是相连的,选择了第一个数字就不能选择最后一个数字,情况就变成第一个数字要么被选择,要么不被选择。 如果第一个数字未被选择,那么就应该求从1到n-1的中所能获得money的最大值temp1,如果第一个数字被选择了,那么就应该求从0到n-2中所能获得money的最大值temp2,返回temp1和temp2中较大的一个即可。
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.
思路:与House Robber(/article/8667869.html)的区别是,整个数组的第一个数字和第二个数字是相连的,选择了第一个数字就不能选择最后一个数字,情况就变成第一个数字要么被选择,要么不被选择。 如果第一个数字未被选择,那么就应该求从1到n-1的中所能获得money的最大值temp1,如果第一个数字被选择了,那么就应该求从0到n-2中所能获得money的最大值temp2,返回temp1和temp2中较大的一个即可。
public class Solution { public int rob(int[] nums) { int n=nums.length; if(n==0) return 0; int best0=0; int best1=0; if(n==1) return nums[0]; for(int i=1;i<n;i++) { int temp=best0; best0=best0>best1 ? best0 :best1; best1=temp+nums[i]; } int temp1= Math.max(best0,best1); best0=0; best1=0; for(int i=0;i<n-1;i++) { int temp=best0; best0=best0>best1 ? best0 :best1; best1=temp+nums[i]; } int temp2=Math.max(best0,best1); return Math.max(temp1,temp2); } }
相关文章推荐
- Nginx发布1.9.0版本,新增支持TCP代理和负载均衡的stream模块
- Communication System(dp)
- openwrt su : must be suid to work properly
- Azure REST API (2) Azure Storage
- 装 MSDE2000 后,1433 端口未监听的问题[整理转贴]
- 升级版控制台神兽
- hdu2018 dp
- Communication System(dp)
- android 第三方 Im
- 输入日期及提醒事件并输出
- 分享干货 码农必备各种API20
- ThinkPHP自动验证分析
- Java IO最详解
- PL/SQL语句学习之使用while、loop和for三种循环打印数字的1-10
- HDU 4710 Balls Rearrangement
- 2013阿里巴巴安全工程师笔试试题_复习使用
- [转]svn: E200030: sqlite[S11]: database disk image is malformed
- How to:如何让Installshield显示正确的软件所需空间--网友冰块先生贡献
- HDU 5396 Expression (数学期望+区间DP)
- 电脑问题--20140323 outlook邮件内链接打不开解决办法