Skip to content

Commit b81414f

Browse files
add post '(Leetcode) 198 - House Robber'
1 parent f5b90e7 commit b81414f

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

_posts/2024-07-03-leetcode-198.md

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 198 - House Robber
4+
categories: [스터디-알고리즘]
5+
tags:
6+
[
7+
자바,
8+
java,
9+
리트코드,
10+
Leetcode,
11+
알고리즘,
12+
array,
13+
dp,
14+
danamic programming,
15+
max,
16+
]
17+
date: 2024-07-03 13:00:00 +0900
18+
toc: true
19+
---
20+
21+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
22+
23+
[https://neetcode.io/practice](https://neetcode.io/practice)
24+
25+
---
26+
27+
[https://leetcode.com/problems/house-robber/](https://leetcode.com/problems/house-robber/)
28+
29+
풀어본 적이 없는데 풀어본 것 같은 느낌이 들 정도로 전형적인 dp 문제 형태이다.
30+
31+
dp array를 이용해서
32+
33+
- 0 번째 집을 방문할 경우 최대로 얻을 수 있는 값
34+
- 1 번째 집을 방문할 경우 최대로 얻을 수 있는 값
35+
- 2 번째 집을 방문할 경우 최대로 얻을 수 있는 값
36+
- 3 번째 집을 방문할 경우 최대로 얻을 수 있는 값
37+
- ...
38+
- n 번째 집을 방문할 경우 최대로 얻을 수 있는 값
39+
40+
이런식으로 계속 계산해 나간다.
41+
42+
n이 2보다 클 때 n 번째 집을 방문할 경우 최대로 얻을 수 있는 값은 `Math.max(nums[i] + dp[i - 2], nums[i] + dp[i - 3])` 이다.
43+
이는 연속된 집을 방문하지 못한다는 특성에 의한 것이다.
44+
45+
## 내가 작성한 풀이
46+
47+
```java
48+
public class Solution {
49+
public int rob(int[] nums) {
50+
int[] dp = new int[nums.length];
51+
int max = 0;
52+
53+
if (nums.length == 1) {
54+
return nums[0];
55+
}
56+
57+
if (nums.length == 2) {
58+
return Math.max(nums[0], nums[1]);
59+
}
60+
61+
if (nums.length == 3) {
62+
return Math.max(nums[2] + nums[0], nums[1]);
63+
}
64+
65+
dp[0] = nums[0];
66+
dp[1] = nums[1];
67+
dp[2] = nums[2] + nums[0];
68+
max = Math.max(dp[2], dp[1]);
69+
for (int i = 3; i < nums.length; i++) {
70+
dp[i] = Math.max(nums[i] + dp[i - 2], nums[i] + dp[i - 3]);
71+
max = Math.max(max, dp[i]);
72+
}
73+
return max;
74+
}
75+
}
76+
```
77+
78+
### TC, SC
79+
80+
시간 복잡도는 O(n), 공간 복잡도는 O(n) 이다.

0 commit comments

Comments
 (0)