House Robber 解答
Question
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.
Solution 1 -- DP
The key is to find the relation dp[i] = Math.max(dp[i-1], dp[i-2]+num[i-1])
. Time complexity O(n), space cost O(n).
1 public class Solution { 2 public int rob(int[] nums) { 3 if (nums == null || nums.length < 1) 4 return 0; 5 int length = nums.length; 6 int[] dp = new int[length + 1]; 7 dp[0] = 0; 8 dp[1] = nums[0]; 9 for (int i = 2; i <= length; i++) { 10 dp[i] = Math.max(dp[i - 1], nums[i - 1] + dp[i - 2]); 11 } 12 return dp[length]; 13 } 14 }
Solution 2
Another method is to use two counters, one for even number and the other for odd number.
1 public class Solution { 2 public int rob(int[] nums) { 3 if (nums == null || nums.length < 1) 4 return 0; 5 int odd = 0, even = 0, length = nums.length; 6 for (int i = 0; i < length; i++) { 7 if (i % 2 == 0) { 8 even += nums[i]; 9 even = even > odd ? even : odd; 10 } else { 11 odd += nums[i]; 12 odd = odd > even ? odd : even; 13 } 14 } 15 return even > odd ? even : odd; 16 } 17 }