Skip to content

Commit

Permalink
3. House Robber II
Browse files Browse the repository at this point in the history
  • Loading branch information
Sunjae95 committed Nov 13, 2024
1 parent def6a43 commit 08706ec
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions house-robber-ii/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @description
* 점화식: dp[i] = Math.max(dp[i - 1], dp[i - 2] + current);
* μˆœνšŒν•œλ‹€λŠ” 쑰건이 μžˆμœΌλ―€λ‘œ λ‹€μŒκ³Ό 같이 λΆ„κΈ°μ²˜λ¦¬ ν•  수 μžˆλ‹€.
* 1. 처음이 선택 O λ§ˆμ§€λ§‰ X
* 2. 처음이 선택 X λ§ˆμ§€λ§‰ μƒκ΄€μ—†μŒ
*
* n = length of nums
* time complexity: O(n)
* space complexity: O(n)
*/
var rob = function (nums) {
if (nums.length === 1) return nums[0];
if (nums.length === 2) return Math.max(nums[0], nums[1]);

const hasFirst = Array.from({ length: nums.length }, (_, i) =>
i < 2 ? nums[0] : 0
);
const noFirst = Array.from({ length: nums.length }, (_, i) =>
i === 1 ? nums[i] : 0
);
for (let i = 2; i < nums.length; i++) {
hasFirst[i] = Math.max(hasFirst[i - 1], hasFirst[i - 2] + nums[i]);
noFirst[i] = Math.max(noFirst[i - 1], noFirst[i - 2] + nums[i]);
if (i === nums.length - 1) {
hasFirst[i] = Math.max(hasFirst[i - 1], hasFirst[i - 2]);
}
}

return Math.max(hasFirst[nums.length - 1], noFirst[nums.length - 1]);
};

0 comments on commit 08706ec

Please sign in to comment.