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.
可以用动态规划来做。初始化len+1的数组,arr[0]=0,arr[1]=nums[0],下一个arr的
值是它之前的值和之前间隔一个index的值加上nums的最大值。
public int rob(int[] nums) {
if(nums==null||nums.length<=0)
return 0;
int[] arr=new int[nums.length+1];
arr[0]=0;
arr[1]=nums[0];
for(int i=2;i<nums.length+1;i++)
arr[i]=Math.max(arr[i-1], nums[i-1]+arr[i-2]);
return arr[nums.length];
}也可以用两个变量来存储偶数位置和奇数位置的最大值。
public int rob2(int[] nums) {
if(nums==null||nums.length<=0)
return 0;
int even=0;
int odd=0;
for(int i=0;i<nums.length;i++){
if(i%2==0){
even+=nums[i];
even=Math.max(even, odd);
}else{
odd+=nums[i];
odd=Math.max(even, odd);
}
}
return Math.max(even, odd);
}

1429

被折叠的 条评论
为什么被折叠?



