forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHouseRobber.js
More file actions
Latest commit
23 lines (20 loc) · 783 Bytes
/
Copy pathHouseRobber.js
File metadata and controls
23 lines (20 loc) · 783 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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/)
*/
exportconsthouseRobber=(nums)=>{
constlength=nums.length
if(length===0)return0
if(length===1)returnnums[0]
if(length===2)returnMath.max(nums[0],nums[1])
constdp=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(leti=2;i<length;i++){
dp[i]=Math.max(nums[i]+dp[i-2],dp[i-1])
}
returndp[length-1]
}