LeetCode: House Robber Solution
Memoized recusionApproach
Let f(i)
be the maximum amount robbeb starting from house i
At house i
, there are two choices:
- Rob
- Skip
1f(i) = max(rob(i), skip(i))
Implementation
1var rob = function (nums) {2 const memo = {}34 const recursion = i => {5 if (i >= nums.length) return 067 if (memo[i] != null) return memo[i]89 const rob = nums[i] + recursion(i + 2)10 const skip = recursion(i + 1)1112 return (memo[i] = Math.max(rob, skip))13 }1415 return recursion(0)16}
References
Similar problems
Maximum Product Subarray
House Robber II
Paint House
Paint Fence
House Robber III
Non-negative Integers without Consecutive Ones
Coin Path
Delete and Earn
Solving Questions With Brainpower
Count Number of Ways to Place Houses
Comments
Loading comments...
Tags
leetcode
recursion
dynamic programming
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
String manipulation
Previous Post
Backtracking with chosen state