题目描述:
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[] nums) {
int best0 = 0; //choose current house
int best1 = 0; // do not choose current house
for(int i = 0; i < nums.length; i++){
int temp = best0;
best0 = Math.max(best0, best1);
best1 = temp + nums[i];
}
return Math.max(best0, best1);
}
}