原题链接在这里:https://leetcode.com/problems/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
题解:
DP问题. state 到当前house能偷到的最多钱. 转移方程 dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i-1]).
优化空间. 只用维护前面两个值就够.
Time Complexity: O(n). Space: O(1).
AC Java:
1 class Solution { 2 public int rob(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 7 int include = 0; 8 int exclude = 0; 9 for(int i = 0; i<nums.length; i++){ 10 int in = include; 11 int ex = exclude; 12 exclude = Math.max(in, ex); 13 include = ex + nums[i]; 14 } 15 16 return Math.max(include, exclude); 17 } 18 }