Skip to content

Commit 52742bd

Browse files
committed
house robber solution
1 parent 94f2c10 commit 52742bd

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

house-robber/nancyel.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* time complexity: O(n) - iterate over a loop
3+
* space complexity: O(n) - dp array
4+
*
5+
* comment: initial naive implementation: simple odd/even alternation, which may return result that is "accidentally correct."
6+
*/
7+
function rob(nums: number[]): number {
8+
// early return
9+
if (nums.length === 0) return 0;
10+
if (nums.length === 1) return nums[0];
11+
12+
const dp: number[] = new Array(nums.length);
13+
dp[0] = nums[0];
14+
dp[1] = Math.max(nums[0], nums[1]);
15+
16+
for (let i = 2; i < nums.length; i++) {
17+
// select either 1) current + best from 2 houses ago or 2) skip current, best from previous
18+
dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]);
19+
}
20+
21+
return dp[nums.length - 1]; // max money from all houses
22+
}

0 commit comments

Comments
 (0)