LeetCode 213 House Robber II
2016-04-14 10:48
190 查看
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.
被打劫的是一个环,所以如果抢了第一家,就不能抢最后一家。所以我们可以分别计算抢了从第二家到最后一家与抢从第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。
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.
被打劫的是一个环,所以如果抢了第一家,就不能抢最后一家。所以我们可以分别计算抢了从第二家到最后一家与抢从第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。
public int rob2(int[] nums) { if (nums.length <= 0) return 0; if (nums.length == 1) return nums[0]; //打劫第1家到倒数第2家的最大值 int a = nums[0], b = Math.max(nums[1], nums[0]); for (int i = 2; i < nums.length - 1; i++) { int tmp = b; b = Math.max(a + nums[i], b); a = tmp; } if (nums.length <= 2) return b; //打劫第2家到最后一家的最大值 int c = nums[1], d = Math.max(nums[1], nums[2]); for (int i = 3; i < nums.length; i++) { int tmp = d; d = Math.max(c + nums[i], d); c = tmp; } return Math.max(b, d); }
相关文章推荐
- android---HandlerThread源码分析
- Android Studio 引入编写好的.so库
- 同步异步动态引入js文件
- 转spring aop实现业务层mysql 读写分离
- 搜索算法2之1008
- ModelAndView 简单介绍
- jpg/png格式图片转eps格式的方法总结
- 关于CGImageRef
- CocoaPods详解之----使用篇
- cmd命令大全
- How do you build a database?
- Atitit. 注册表操作查询 修改 api与工具总结 java c# php js python 病毒木马的原理
- 视频播放器
- tmux 常用快捷键
- 基于NGUI的循环滑动组件
- ZOJ-3211-Dream City-DP背包问题+贪心
- PAT1018锤子剪刀布 (20)
- android发布市场比较
- Atitit. 注册表操作查询 修改 api与工具总结 java c# php js python 病毒木马的原理
- caffe教程翻译:Alex’s CIFAR-10 tutorial, Caffe style