House Robber
Problem
You are given an integer array nums where nums[i] represents the amount of money the ith house has. The houses are arranged in a straight line, i.e. the ith house is the neighbor of the (i-1)th and (i+1)th house.
You are planning to rob money from the houses, but you cannot rob two adjacent houses because the security system will automatically alert the police if two adjacent houses were both broken into.
Return the maximum amount of money you can rob without alerting the police.
Examples
Example 1:
Input: nums = [1,1,3,3]
Output: 4
Explanation: nums[0] + nums[2] = 1 + 3 = 4.
Example 2:
Input: nums = [2,9,8,3,6]
Output: 16
Explanation: nums[0] + nums[2] + nums[4] = 2 + 8 + 6 = 16.
Constraints
1 <= nums.length <= 1000 <= nums[i] <= 100
You should aim for a solution as good or better than O(n) time and O(n) space, where n is the number of houses.
Solution
Current index is the most we can rob up to and including that house. The value for a given index is the maximum of the previous house (since we can’t rob current house if we rob the previous house) and the current house + 2 indices previously
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.empty()) { return 0; }
if (nums.size() == 1) { return nums[0]; }
nums[1] = std::max(nums[0], nums[1]);
for (int i = 2; i < nums.size(); ++i) {
nums[i] = std::max(nums[i - 1], nums[i] + nums[i - 2]);
}
return nums[nums.size() - 1];
}
};