> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

House Robber

Leetcode Problem 198: House Robber

Problem Summary

You are a robber planning to rob houses along a street. Each house contains a certain amount of money. Adjacent houses have connected security systems, so robbing two neighboring houses triggers an alarm. Given an array of non-negative integers representing the money in each house, return the maximum amount you can rob without robbing any two adjacent houses. The array has between 1 and 100 elements, and each value is a non-negative integer up to 400.

Techniques

  • Array
  • Dynamic Programming

Solution

function rob(nums: number[]): number {
    let withoutPreviousHouse = 0
    let previousHouse = 0

    for (let i = 0; i < nums.length; i++) {
        const result = Math.max(
            nums[i] + withoutPreviousHouse,
            previousHouse
        )
        withoutPreviousHouse = previousHouse
        previousHouse = result
    }

    return previousHouse
};

console.log(rob([1, 2, 3, 1])) // 4
console.log(rob([2, 7, 9, 3, 1])) // 12