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.
思路:
動(dòng)態(tài)規(guī)劃
對(duì)于第i個(gè)房間來說,可以采取搶或不搶。
如果搶的話,截止到當(dāng)前房間能獲得的最大money等于前i-2個(gè)房間最大money和當(dāng)前房間的money。
如果不搶留瞳,截止當(dāng)當(dāng)前房間能獲得的最大money等于前i-1個(gè)房間得到的最大money。
用數(shù)組money表示截止到第i個(gè)房間能搶到的最大錢數(shù),可以得到遞推式:
money[i] = Math.max(money[i-1], money[i-2] + rooms[i-1]) (i從1開始)
money[1] = rooms[0];
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] maxMoney = new int[nums.length+1];
maxMoney[1] = nums[0];
for (int i = 2; i <= nums.length; i++) {
maxMoney[i] = Math.max(maxMoney[i-1], maxMoney[i-2] + nums[i-1]);
}
return maxMoney[nums.length];
}