Skip to content

Commit c252df5

Browse files
authored
feat: add houseRobber implementation (TheAlgorithms#1282)
1 parent 002b10a commit c252df5

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @function houseRobber
3+
* @description 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.
4+
* @param {number[]} nums
5+
* @return {number}
6+
* @see [Leetcode link](https://leetcode.com/problems/house-robber/)
7+
*/
8+
export const houseRobber = (nums) => {
9+
const length = nums.length
10+
11+
if (length === 0) return 0
12+
if (length === 1) return nums[0]
13+
if (length === 2) return Math.max(nums[0], nums[1])
14+
15+
const dp = Array(length) // last element of this array always contains biggest loot possible
16+
dp[0] = nums[0]
17+
dp[1] = Math.max(nums[0], nums[1])
18+
19+
for (let i = 2; i < length; i++) {
20+
dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1])
21+
}
22+
return dp[length - 1]
23+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { houseRobber } from '../HouseRobber'
2+
3+
describe('houseRobber', () => {
4+
it('expects to return 0 when argument is empty array', () => {
5+
expect(houseRobber([])).toBe(0)
6+
})
7+
8+
it('expects to return element at index 0 when argument is array of length one', () => {
9+
expect(houseRobber([9])).toBe(9)
10+
})
11+
12+
it('expects to return greater number when argument is an array of length two', () => {
13+
expect(houseRobber([3, 6])).toBe(6)
14+
})
15+
16+
it('expects to return the maximum loot possible', () => {
17+
expect(houseRobber([1, 2, 3, 1])).toBe(4)
18+
expect(houseRobber([2, 7, 9, 3, 1])).toBe(12)
19+
})
20+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy