標籤:from automatic list size bsp 數組 represent lan style
題目:
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.
題意及分析:給出一個非負的數組,從頭到尾遍曆,求取一個能得到最大和的序列,其中每兩個元素不能相鄰。使用動態規劃,到當前元素i的最大收益只有兩種情況:
(1)前一個元素得到最大值
(2)從前一個元素的前一個元素加上當前元素得到最大值
比較兩個值,取最大值為當前點的最大收益
代碼:
public class Solution { public int rob(int[] nums) { int max=Integer.MIN_VALUE; int length=nums.length; if(length==0) return 0; if(length==1) return nums[0]; if(length==2) return Math.max(nums[0], nums[1]); int[] res = new int[length]; res[0]=nums[0]; res[1]=Math.max(nums[0], nums[1]); max=Math.max(nums[0], nums[1]); for(int i=2;i<length;i++){ max=Math.max(res[i-2]+nums[i], res[i-1]); res[i]=max; } return res[length-1]; }}
[LeetCode] 198. House Robber Java