House Robber II

Published by

on

Problem

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

Solution

// f[x][0] = x 개 집이 있을 때, x 번째 집을 털고 + 첫 번째 집을 안 터는 경우 털 수 있는 최대 
// f[x][1] = x 개 집이 있을 때, x 번째 집을 털고 + 첫 번째 집을 터는 경우 털 수 있는 최대 
// f[x][0] = max(f[x-1][0], f[x-2][0] + g[x])
// f[x][1] = max(f[x-1][1], f[x-2][1])
// f[x] = max(f[x][0], f[x][1])
class Solution {
    private int[][] f;
    private int n;

    public int rob(int[] nums) {
        this.n = nums.length;
        this.f = new int[n][2];

        if (n == 0) {
            return 0;
        } else if (n == 1) {
            return nums[0];
        }

        f[0][0] = 0;
        f[1][0] = nums[1];
        for (int i=2;i<n;i++) {
            f[i][0] = Math.max(f[i-1][0], f[i-2][0] + nums[i]);
        }

        f[0][1] = nums[0];
        f[1][1] = nums[0];
        for (int i=2;i<n-1;i++) {
            f[i][1] = Math.max(f[i-1][1], f[i-2][1] + nums[i]);
        }
        f[n-1][1] = f[n-2][1];

        return Math.max(f[n-1][0], f[n-1][1]);
    }
}
  • 2차원 배열을 이용해 첫번째 집을 턴 경우와 안 턴 경우를 나눠서 DP 진행!

Leave a comment