Skip to content

Commit

Permalink
Feat: 213. House Robber II
Browse files Browse the repository at this point in the history
  • Loading branch information
HC-kang committed Nov 16, 2024
1 parent bf1cca5 commit 1058511
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions house-robber-ii/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* https://leetcode.com/problems/house-robber-ii
* T.C. O(n)
* S.C. O(1)
*/
function rob(nums: number[]): number {
if (nums.length === 1) return nums[0];
if (nums.length === 2) return Math.max(nums[0], nums[1]);
if (nums.length === 3) return Math.max(nums[0], nums[1], nums[2]);

function robHelper(nums: number[]): number {
let prev = 0;
let curr = 0;
for (let i = 0; i < nums.length; i++) {
const temp = curr;
curr = Math.max(prev + nums[i], curr);
prev = temp;
}
return curr;
}

const robFirst = robHelper(nums.slice(0, nums.length - 1));
const robLast = robHelper(nums.slice(1));

return Math.max(robFirst, robLast);
}

0 comments on commit 1058511

Please sign in to comment.