diff --git a/Dynamic-Programming/Sliding-Window/HouseRobber.js b/Dynamic-Programming/Sliding-Window/HouseRobber.js new file mode 100644 index 0000000000..8d8dd5b43e --- /dev/null +++ b/Dynamic-Programming/Sliding-Window/HouseRobber.js @@ -0,0 +1,23 @@ +/** + * @function houseRobber + * @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. + * @param {number[]} nums + * @return {number} + * @see [Leetcode link](https://leetcode.com/problems/house-robber/) + */ +export const houseRobber = (nums) => { + const length = nums.length + + if (length === 0) return 0 + if (length === 1) return nums[0] + if (length === 2) return Math.max(nums[0], nums[1]) + + const dp = Array(length) // last element of this array always contains biggest loot possible + dp[0] = nums[0] + dp[1] = Math.max(nums[0], nums[1]) + + for (let i = 2; i < length; i++) { + dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]) + } + return dp[length - 1] +} diff --git a/Dynamic-Programming/Sliding-Window/test/HouseRobber.test.js b/Dynamic-Programming/Sliding-Window/test/HouseRobber.test.js new file mode 100644 index 0000000000..cb32498825 --- /dev/null +++ b/Dynamic-Programming/Sliding-Window/test/HouseRobber.test.js @@ -0,0 +1,20 @@ +import { houseRobber } from '../HouseRobber' + +describe('houseRobber', () => { + it('expects to return 0 when argument is empty array', () => { + expect(houseRobber([])).toBe(0) + }) + + it('expects to return element at index 0 when argument is array of length one', () => { + expect(houseRobber([9])).toBe(9) + }) + + it('expects to return greater number when argument is an array of length two', () => { + expect(houseRobber([3, 6])).toBe(6) + }) + + it('expects to return the maximum loot possible', () => { + expect(houseRobber([1, 2, 3, 1])).toBe(4) + expect(houseRobber([2, 7, 9, 3, 1])).toBe(12) + }) +})