아카이브

[PS] Leet | 213. 빈집 털이 II 본문

CS/PS

[PS] Leet | 213. 빈집 털이 II

Rayi 2025. 4. 10. 11:10

문제

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

예시

Example 1:
Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.

 

Example 2:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.


Example 3:
Input: nums = [1,2,3]
Output: 3

조건

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000

일반적인 DP로 해결하나, 마지막을 조금 다르게 처리해주어야 합니다.

 

nums가 원순열로 주어져 있기 때문에, 마지막 i+1개 순열에 대해서는 (0번째 ~ i-1번째)에서의 값(1번째 ~ i번째)에서의 값을 비교해주면 됩니다.

 

단, nums의 길이가 1일 때는 요소가 하나 밖에 없으므로 해당 요소를 반환해주어야 합니다.

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function(nums) {
    const robLin = (arr) => {
        lst = new Array(arr.length + 1).fill(0);
        lst[0] = 0;
        lst[1] = arr[0];

        for (let i=2; i<=arr.length; ++i) {
            lst[i] = Math.max(lst[i-2] + arr[i-1], lst[i-1]);
        }

        return lst[arr.length];
    }
    
    return (nums.length > 1)? Math.max(robLin(nums.slice(0, nums.length-1)), robLin(nums.slice(1))) : nums[0];
};
728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 207. 과목 스케쥴  (0) 2025.04.19
[PS] Leet | 133. 그래프 복사  (0) 2025.04.11
[PS] Leet | 1143. 가장 긴 공통 배열  (0) 2025.04.05
[PS] Leet | 300. 가장 긴 증가 수열  (0) 2025.04.02
[PS] Leet | 322. 동전 교환  (0) 2025.03.28
Comments