原題連接在這裏:https://leetcode.com/problems/house-robber/html
題目:post
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 url
題解:spa
DP問題. state 到當前house能偷到的最多錢. 轉移方程 dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i-1]). code
優化空間. 只用維護前面兩個值就夠.htm
Time Complexity: O(n). Space: O(1).blog
AC Java:leetcode
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 }
跟上House Robber II, House Robber III.get