213. House Robber II

2024. 11. 30. 18:29·Algorithm/LeetCode

문제

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

Constraints:

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

Solution

class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        if(n==1) return nums[0];

        return Math.max(getMaxRob(nums,0, n-1), getMaxRob(nums,1,n));
    }


    public int getMaxRob(int[] nums, int start, int end) {
        int maxRob = 0;
        int preRob = 0;

        for(int i=start;i<end;i++) {
            int curVal = nums[i];
            int temp = Math.max(maxRob, curVal + preRob);
            preRob = maxRob; 
            maxRob = temp;
        }

        return maxRob;
    }
}

회고

House Robber 문제는 "각 집에는 일정 금액의 돈이 있으며, 인접한 집은 동시에 털 수 없다"는 조건을 만족하면서 최대 금액을 얻는 문제입니다. 여기에 House Robber 2에서는 "처음과 마지막 집이 인접하다"는 조건이 추가되었습니다. 즉, 집들이 원형으로 배열되어 있으므로 처음과 마지막 집을 동시에 털 수 없습니다.

 

원형 구조를 처리하기 위해:

  • [0, n-1] 범위의 집들만 고려한 경우
  • [1, n] 범위의 집들만 고려한 경우 두 가지로 나누어 getMaxRob 메서드를 호출하고, 최댓값을 반환합니다.

 

dp 배열을 사용하지 않고, 대신 현재 값(maxRob), 이전 값(preRob), 그리고 현재 집의 금액(curVal)을 활용하여 문제를 해결했습니다.이를 통해 공간 복잡도를 O(n)에서 O(1)로 최적화할 수 있습니다.

for(int i=start;i<end;i++) {
            int curVal = nums[i];
            int temp = Math.max(maxRob, curVal + preRob);
            preRob = maxRob; 
            maxRob = temp;
        }
  • curVal: 현재 집의 금액
  • maxRob: 현재 집까지 털었을 때의 최대 금액
  • preRob: 바로 이전 집까지 털었을 때의 최대 금액

 

 

'Algorithm > LeetCode' 카테고리의 다른 글

403. Frog Jump  (0) 2025.04.04
[DP] 91. Decode Ways  (0) 2024.12.01
377. Combination Sum IV  (0) 2024.11.17
1143. Longest Common Subsequence  (0) 2024.11.16
139. Word Break  (0) 2024.11.11
'Algorithm/LeetCode' 카테고리의 다른 글
  • 403. Frog Jump
  • [DP] 91. Decode Ways
  • 377. Combination Sum IV
  • 1143. Longest Common Subsequence
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (209)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (14)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • GitHub
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    @JsonNaming
    Climbing Stairs
    RR
    BFS
    pacific atlantic water flow
    Oauth2
    디자인 패턴
    algorithm
    lower bounded wildcards
    Reorder List
    Generic
    AuthenticationSuccessHandler
    wildcards
    OS
    rotting oranges
    LinkedList
    minimum number of arrows to burst balloons
    socar
    트랜잭션
    제네릭
    JSCode
    runner 기법
    fcfs
    clone graph
    준영속 엔티티
    운영체제
    Process
    추상화 클래스
    Thread
    @JsonProperty
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
213. House Robber II
상단으로

티스토리툴바