Skip to content

Commit e11a20f

Browse files
week10 mission house-robber-ii
1 parent eee2a92 commit e11a20f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
- 문제: https://leetcode.com/problems/house-robber-ii/
2+
- 풀이: https://algorithm.jonghoonpark.com/2024/07/03/leetcode-213
3+
4+
## 내가 작성한 풀이
5+
6+
```java
7+
public class Solution {
8+
public int rob(int[] nums) {
9+
if (nums.length == 1) {
10+
return nums[0];
11+
}
12+
13+
if (nums.length == 2) {
14+
return Math.max(nums[0], nums[1]);
15+
}
16+
17+
if (nums.length == 3) {
18+
return Math.max(nums[2], Math.max(nums[0], nums[1]));
19+
}
20+
21+
22+
return Math.max(getMaxInRange(nums, 0, nums.length - 1), getMaxInRange(nums, 1, nums.length));
23+
}
24+
25+
public int getMaxInRange(int[] nums, int start, int end) {
26+
int[] dp = new int[nums.length];
27+
int max;
28+
dp[start] = nums[start];
29+
dp[start + 1] = nums[start + 1];
30+
dp[start + 2] = nums[start + 2] + nums[start];
31+
max = Math.max(dp[start + 2], dp[start + 1]);
32+
for (int i = start + 3; i < end; i++) {
33+
dp[i] = Math.max(nums[i] + dp[i - 2], nums[i] + dp[i - 3]);
34+
max = Math.max(max, dp[i]);
35+
}
36+
return max;
37+
}
38+
}
39+
```
40+
41+
### TC, SC
42+
43+
시간 복잡도는 O(n), 공간 복잡도는 O(n) 이다.

0 commit comments

Comments
 (0)