[LeetCode] House Robber

2025. 2. 25. 15:53·공부/코딩테스트 | 알고리즘

문제

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems 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.

 

예시

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.

Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

풀기

문제를 요약하자면 강도는 이틀에 한 번 집을 털 수 있고 최대로 이익을 낼 수 있는 값을 출력하라는 말이다.

즉, 배열의 값이 반복되지 않도록 하라는 뜻.

 

DP 문제에 해당하므로 점화식을 찾도록 하자.

집을 반복해서 털 수 없다고 했으니

  • dp[i - 2] + nums[i] -> 현재 집 털기
  • dp[i - 1] -> 현재 집 털지 않기
  • 현재 집을 털지 않기 or 현재 집과 이전 집을 건너뛰고 털기 중 최댓값 선택

따라서 점화식은 아래와 같다.

dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])

 


결과

class Solution {
    fun rob(nums: IntArray): Int {
        var prev1 = nums[0] // 이전 집 (dp[i - 1])
        var prev2 = 0 // 전전 집 (dp[i - 2])

        for (i in 1 until nums.size) {
            val current = maxOf(prev1, nums[i] + prev2)
            prev2 = prev1
            prev1 = current
        }

        return prev1
    }
}

 

'공부 > 코딩테스트 | 알고리즘' 카테고리의 다른 글

[LeetCode] Maximum Depth of Binary Tree  (0) 2025.02.27
[LeetCode] Min Stack  (0) 2025.02.26
[LeetCode] Maximum Subarray  (0) 2025.02.24
[LeetCode] Climbing Stairs  (0) 2025.02.24
[프로그래머스] 입양 시각 구하기(2)  (0) 2022.02.15
'공부/코딩테스트 | 알고리즘' 카테고리의 다른 글
  • [LeetCode] Maximum Depth of Binary Tree
  • [LeetCode] Min Stack
  • [LeetCode] Maximum Subarray
  • [LeetCode] Climbing Stairs
나는 유찌
나는 유찌
쩌리쨩
  • 나는 유찌
    유찌 개발 일기
    나는 유찌
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 사이드 프로젝트
        • 게시판
        • 블로그(Spring boot + React.js ..
      • 데이터베이스
        • SQLD
      • 이슈 해결
      • Front
        • Javascript
        • Vue.js
        • HTML+CSS
      • Backend
        • Spring
        • ORM
        • JAVA
      • 공부
        • HTTP
        • OOP
        • 이것저것
        • 코딩테스트 | 알고리즘
      • Computer Science
        • Computer architecture
        • 데이터베이스
        • 운영체제
      • 일상
        • 독서
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    role scope
    mssql
    추리소설
    Spring Security AccessDecisionManager
    pessimisticlock
    히가시노 게이고
    phantom read
    Spring Boot
    mysql 격리수준
    jwt
    권한 scope 처리
    LeetCode
    DIRTY READ
    독서
    spring 격리수준
    한국소설
    JWT이란?
    AccessDecisionVoter
    Kotlin AntPathMatcher
    웹 개발
    redis 분산락
    Kotlin AccessDecisionManager
    Access Token Refresh Token
    access token
    Access token 재발급
    jwt 로그인 구현
    refresh token
    AntPathMatcher
    Spring boot에서 JWT 구현
    spring
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
나는 유찌
[LeetCode] House Robber
상단으로

티스토리툴바