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.
Similar:
213. House Robber II
337. House Robber III
152. Maximum Product Subarray
256. Paint House
1 public class Solution { 2 public int rob(int[] nums) { 3 int include = 0, exclude = 0; 4 for (int i = 0; i < nums.length; i++) { 5 int in = include, ex = exclude; 6 include = ex + nums[i]; 7 exclude = Math.max(ex, in); 8 } 9 return Math.max(include, exclude); 10 } 11 }
1 public class Solution { 2 public int rob(int[] nums) { 3 if (nums.length == 0) return 0; 4 if (nums.length == 1) return nums[0]; 5 int max = nums[0] > nums[1] ? nums[0] : nums[1]; 6 7 for (int i = 2; i < nums.length; i++) { 8 if (i == 2) nums[i] += nums[0]; 9 else { 10 nums[i] += (nums[i-3] > nums[i-2] ? nums[i-3] : nums[i-2]); 11 } 12 max = max > nums[i] ? max : nums[i]; 13 } 14 15 return max; 16 } 17 }