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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array
nums
representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
INTUITION :
eg: [1,2,3,1], output = 4
first we can think to rob 0th element = 1
but, cannot rob 1th element, i.e 2, but 1 is larger than 0, so rob 1 and skip 2. so current rob = 2
now 2th element is 3, so, either rob 0 and 2 or go with 1, 3+1 =4 is larger than 2, so current rob = 4
Now, 3th element is 1, so rob 3&1, or go with 2th => 2+1 = 3 is smaller than 3+1 =4, so current rob = 4 (ANS)
APPROACH :
Initialize a dp[] array of size = array size.
dp[0] = 1, dp[1] = Max(2, dp[1]) = 2
now run a for loop from 2 to n. Ans use this formula :
dp[i] = Max(dp[i-1], dp[i-2]+arr[i])
return
dp[n-1]
CODE (in java) :
public int rob(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
if (nums.length == 2) return (int)Math.max(nums[0], nums[1]);
dp[0] = nums[0];
dp[1] = Math.max(dp[0], nums[1]);
for (int i = 2; i < nums.length; i++) {
dp[i] = Math.max(dp[i-1], nums[i]+dp[i-2]);
}
return dp[n-1];
}