[M] 198. House Robber

YJ·2025년 2월 15일

leetcode

목록 보기
3/100

https://leetcode.com/problems/house-robber/

문제

집 별로 돈 주어진 배열

인접한 두 집이 털리면 경찰 신고됨

최대로 도둑질할 수 있는 금액

답안

public int rob(int[] nums) {
	int len = nums.length;
    if (len == 1) {
        return nums[0];
    }
    int[] dp = new int[len];
    dp[0] = nums[0];
    dp[1] = Math.max(nums[0], nums[1]);
    for (int i = 2; i < len; i++) {
        dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i]);
    }
    return dp[len-1];
}

메모

배열이 있으면 특정 index 에 대한 정답은 항상 같음 -> DP

"dp[] 배열은 = 0번부터 i번 집까지 고려했을 때 얻을 수 있는 최대 금액" (선택 여부 문제)

nums.length 범위가 1도 포함한다는 점 note!

public int rob(int[] num) {
    int rob = 0; //max monney can get if rob current house
    int notrob = 0; //max money can get if not rob current house
    for(int i=0; i<num.length; i++) {
        int currob = notrob + num[i]; //if rob current value, previous house must not be robbed
        notrob = Math.max(notrob, rob); //if not rob ith house, take the max value of robbed (i-1)th house and not rob (i-1)th house
        rob = currob;
    }
    return Math.max(rob, notrob);
}

(https://leetcode.com/problems/house-robber/solutions/55695/java-dp-solution-o-n-runtime-and-o-1-space-with-inline-comment/?envType=study-plan-v2&envId=leetcode-75)

요런 코드도 직관적이고 좋다.. 초기값 세팅해줄 필요가 없음

profile
Hello

0개의 댓글