Question:
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.
题意:给定一个非负数组num[],相邻的元素不能同时被加,求能得到的最大和。
求解思路:动态规划。
f[i]中存储当前能获取的最多钱数。递推公式为:f[i]=max(n+f(n-2),f(n-1)),,初始化:f(0)=num[0],f[1]=max(num[0],num[1])。
public int rob(int[] num) {
int N=num.length;
if(N==0) return 0;
if(N==1) return num[0];
if(N==2) return Math.max(num[0],num[1]);
int money[]=new int[N];
money[0]=num[0];
money[1]=Math.max(num[0],num[1]);
for(int i=2;i<N;i++){
money[i]=Math.max(num[i]+money[i-2],money[i-1]);
}
return money[N-1];
}