House Robber
LeetCode: House Robber
Problem:
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.
- Analysis:
Let dp[i] is the max value sum of non-adjacent house at i.
dp[i] value will from dp[i - 1] (not choose nums[i]) or nums[i] + dp[i - 2] (choose nums[i] but not adjacent)
dp[i] = max (dp[i - 1], nums[i] + dp[i - 2]).
- Code - Java:
class Solution {
public int rob(int[] nums) {
int len = nums.length;
if (len <= 0) {
return 0;
}
int[] dp = new int[len + 1];
dp[1] = nums[0];
for (int i = 2; i <= len; i++) {
dp[i] = Math.max(dp[i - 1], nums[i - 1] + dp[i - 2]);
}
return dp[len];
}
}
- Code - C++:
class Solution {
public:
int rob(vector<int>& nums) {
int len = nums.size();
if (len <= 0) {
return 0;
}
vector<int> dp((len + 1), 0);
dp[1] = nums[0];
for (int i = 2; i <= len; i++) {
dp[i] = max(dp[i - 1], nums[i - 1] + dp[i - 2]);
}
return dp[len];
}
};
- Code - Python:
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
numsLen = len(nums)
if numsLen <= 0:
return 0
dp = [0 for i in range((numsLen + 1))]
dp[1] = nums[0]
for i in range(2, numsLen + 1):
dp[i] = max(dp[i - 1], nums[i - 1] + dp[i - 2])
return dp[numsLen]
Time Complexity: O(N), N is the length of the input array
Space Complexity: O(N), N is the length of the input array