House Robber

medium dp

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 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.

Inputnums = [3, 8, 4, 9, 2]
Output17
Pick indices 1 and 3: 8 + 9 = 17.

def rob(nums):
    n = len(nums)
    if n == 0: return 0
    dp = [0] * n
    dp[0] = nums[0]
    for i in range(1, n):
        skip = dp[i - 1]
        take = (dp[i - 2] if i >= 2 else 0) + nums[i]
        dp[i] = max(skip, take)
    return dp[-1]
function rob(nums) {
  const n = nums.length;
  if (n === 0) return 0;
  const dp = new Array(n).fill(0);
  dp[0] = nums[0];
  for (let i = 1; i < n; i++) {
    const skip = dp[i - 1];
    const take = (i >= 2 ? dp[i - 2] : 0) + nums[i];
    dp[i] = Math.max(skip, take);
  }
  return dp[n - 1];
}
class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        if (n == 0) return 0;
        int[] dp = new int[n];
        dp[0] = nums[0];
        for (int i = 1; i < n; i++) {
            int skip = dp[i - 1];
            int take = (i >= 2 ? dp[i - 2] : 0) + nums[i];
            dp[i] = Math.max(skip, take);
        }
        return dp[n - 1];
    }
}
int rob(vector<int>& nums) {
    int n = nums.size();
    if (n == 0) return 0;
    vector<int> dp(n, 0);
    dp[0] = nums[0];
    for (int i = 1; i < n; i++) {
        int skip = dp[i - 1];
        int take = (i >= 2 ? dp[i - 2] : 0) + nums[i];
        dp[i] = max(skip, take);
    }
    return dp[n - 1];
}
Time: O(n) Space: O(n) (reducible to O(1))