Skip to content

Commit 63e5452

Browse files
committed
Add week 13 solutions: house-robber
1 parent 33c1b49 commit 63e5452

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

house-robber/gitsunmin.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* https://leetcode.com/problems/house-robber/
3+
* time complexity : O(n)
4+
* space complexity : O(n)
5+
*/
6+
7+
function rob(nums: number[]): number {
8+
const houseCount = nums.length;
9+
10+
if (houseCount === 0) return 0;
11+
if (houseCount === 1) return nums[0];
12+
13+
const maxRobAmount = new Array(houseCount).fill(0);
14+
maxRobAmount[0] = nums[0];
15+
maxRobAmount[1] = Math.max(nums[0], nums[1]);
16+
17+
for (let i = 2; i < houseCount; i++) maxRobAmount[i] = Math.max(maxRobAmount[i - 1], maxRobAmount[i - 2] + nums[i]);
18+
19+
return maxRobAmount[houseCount - 1];
20+
};

0 commit comments

Comments
 (0)