标签:
区别就是用了两个数组,一个强行从第一个开始,一个强行从第二个开始
1 public int rob(int[] nums) { 2 if(nums.length == 0) { 3 return 0; 4 } 5 int len = nums.length; 6 if(len == 1) { 7 return nums[0]; 8 } 9 if(len == 2) { 10 return Math.max(nums[0], nums[1]); 11 } 12 int[] moneyFromFirst = new int[len]; 13 int[] moneyFromSecond = new int[len]; 14 moneyFromFirst[0] = nums[0]; 15 moneyFromFirst[1] = nums[0]; 16 moneyFromSecond[0] = 0; 17 moneyFromSecond[1] = nums[1]; 18 for(int i = 2; i < len; i++) { 19 moneyFromFirst[i] = Math.max(moneyFromFirst[i-2] + nums[i], moneyFromFirst[i-1]); 20 moneyFromSecond[i] = Math.max(moneyFromSecond[i-2] + nums[i], moneyFromSecond[i-1]); 21 } 22 return Math.max(moneyFromFirst[len-2], moneyFromSecond[len-1]); 23 }
标签:
原文地址:http://www.cnblogs.com/warmland/p/5625574.html