From 08706ec1573fc883cf01dc67fbecd2a92808fe04 Mon Sep 17 00:00:00 2001 From: SeonjaeLee Date: Wed, 13 Nov 2024 17:39:17 +0900 Subject: [PATCH] 3. House Robber II --- house-robber-ii/sunjae95.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 house-robber-ii/sunjae95.js diff --git a/house-robber-ii/sunjae95.js b/house-robber-ii/sunjae95.js new file mode 100644 index 000000000..468f37fc9 --- /dev/null +++ b/house-robber-ii/sunjae95.js @@ -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]); +};