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.
题意:给定一个数组,取出数组内的值,求最大值。限定条件是:相邻两个元素只能取其一。
解决思路:动态规划
代码:
public class Solution {
public int rob(int[] num) {
int last = 0;
int now = 0;
int tmp;
for (int n :num) {
tmp = now;
now = Math.max(last + n, now);
last = tmp;
}
return now;
}
}