leetcode 198. House Robber
leetcode 198. House Robber
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个数,那么最大值应该是max(前i-1个数的最大值,第i个数+前i-2个数的最大值)
也就是要么选,要么不选。
之后更新max,max2
max2是原来的max。
public class Solution { public int rob(int[] nums) { int n=nums.length; if (n==0){ return 0; } int max=nums[0]; int max2=0; for (int i=1;i<n;i++){ if (nums[i]+max2>max){ int tempmax2=max2; max2=max; max=nums[i]+tempmax2; }else { max2=max; } } return max; } }