您的位置:首页 > 其它

House Robberm

2015-12-14 00:14 323 查看
题目:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it
will automatically contact the police if two adjacent houses were broken into on the same night.

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 class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int max = 0;
int[] a = new int[nums.length];
a[0] = nums[0];
a[1] = nums[0] > nums[1] ? nums[0] : nums[1];
max = a[1];
for (int i = 2;i < nums.length;i++) {
for (int j = 0;j < i-1;j++) {
if (a[i] < a[j] + nums[i]) {
a[i] = a[j] + nums[i];
if (a[i] > max) {
max = a[i];
}
}
}
}
return max;
}
}


主要是自己开始没搞明白因为都是non-negative integers,所以随着往后遍历,其实最大的和一直都在倒数第一或者倒数第二的位置(因为倒数第三的位置求得的和加上倒数第一的数可能会小于倒数第二的位置的和),所以只要用两个变量来存我们最终要的最大的和就行了,具体代码如下:
public class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int a = 0,b = 0;
for (int i = 0;i < nums.length;i++) {
if (i % 2 == 0) {
a = Math.max(a + nums[i],b);
} else {
b = Math.max(b + nums[i],a);
}
}
return Math.max(a,b);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: