这道题是一道动态规划的题,就是找到当前位置之前不相邻的最大值和当前值相加与相邻的值取最大值就是当前位置能取到的最大值。
讨论的答案比我自己写的质量好,如下
public int rob(int[] nums) {
if(nums.length==0) return 0;
if(nums.length==1) return nums[0];
//Initialize an arrays to store the money
int[] mark = new int[nums.length];
//We can infer the formula from problem:mark[i]=max(num[i]+mark[i-2],mark[i-1])
//so initialize two nums at first.
mark[0] = nums[0];
mark[1] = Math.max(nums[0], nums[1]);
//Using Dynamic Programming to mark the max money in loop.
for(int i=2;i<nums.length;i++){
mark[i] = Math.max(nums[i]+mark[i-2], mark[i-1]);
}
return mark[nums.length-1];
}
其次就是一个空间复杂度更低的
public class Solution {
public int rob(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int now = 0;
int last = 0;
for (int i=0; i<nums.length; i++) {
int temp = last;
last = now;
now = Math.max(now,nums[i]+temp);
}
return now;
}
}
2016/10/5