213. House Robber II
来源:互联网 发布:单片机程序烧入不进去 编辑:程序博客网 时间:2024/05/16 11:15
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.
这个题有环,因此0和最后一个,不能同时出现,怎么解决呢?计算1到n-1的值和2到n的值,取大的。。。
class Solution { public int rob(int[] nums) { if (nums.length == 0) { return 0; } if (nums.length == 1) { return nums[0]; } if (nums.length == 2) { return Math.max(nums[0], nums[1]); } int val1 = robHelper1(nums); int val2 = robHelper2(nums); return Math.max(val1, val2); } private int robHelper1(int[] nums) { //0- n-2 int[] tmp = new int[nums.length]; tmp[0] = nums[0]; tmp[1] = nums[1]; for (int i = 2; i <= nums.length - 1; i++) { tmp[i] = tmp[i - 2] + nums[i]; tmp[i - 1] = Math.max(tmp[i - 2], tmp[i - 1]); } return Math.max(tmp[nums.length - 2], tmp[nums.length - 3]); } private int robHelper2(int[] nums) { //1- n-1 for (int i = 3; i <= nums.length - 1; i++) { nums[i] = nums[i - 2] + nums[i]; nums[i - 1] = Math.max(nums[i - 2], nums[i - 1]); } return Math.max(nums[nums.length - 1], nums[nums.length - 2]); }}
阅读全文
0 0
- 213.House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II
- 213. House Robber II**
- 213. House Robber II
- 213. House Robber II
- 198. House Robber
- 更新
- Android自定义控件总结
- Jzoj3806 小X 的道路修建
- codeforces 865B. Ordering Pizza
- 213. House Robber II
- 「Machine Learning」K-Means Clustering Algorithm from CS229 Lecture Notes
- 集合框架总结
- 使用knowledge-based方法提升词向量的生成质量
- 设计模式读书笔记-----代理模式
- Python3 函数
- 更新
- codeforces 865 C. Buy Low Sell High
- HTTP