您的位置:首页 > 其它

LeetCode 213: House Robber II

2016-05-26 14:58 405 查看

LeetCode 213: House Robber II

思路

在House Robber题的基础上分两种情况:

nums[0]未被打劫;

nums[0]被打劫;

代码

public class Solution {
public int rob(int[] nums) {
int length = nums.length;
if (length == 0) return 0;
if (length == 1) return nums[0];
if (length == 2) return nums[0] > nums[1] ? nums[0] : nums[1];

//first case nums[0] is robbed
int first = nums[0], second = nums[0];
for (int i = 2; i < nums.length - 1; i++) {
int tmp = (first + nums[i]) > second ? (first + nums[i]) : second;
first = second;
second = tmp;
}
int ret = second;
//first case nums[0] is not robbed
first = 0;
second = nums[1];
for (int i = 2; i < nums.length; i++) {
int tmp = (first + nums[i]) > second ? (first + nums[i]) : second;
first = second;
second = tmp;
}
return ret > second ? ret : second;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode