-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add post '(Leetcode) 213 - House Robber ii'
- Loading branch information
1 parent
b81414f
commit f8b6b9b
Showing
1 changed file
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
--- | ||
layout: post | ||
title: (Leetcode) 213 - House Robber ii | ||
categories: [스터디-알고리즘] | ||
tags: | ||
[ | ||
자바, | ||
java, | ||
리트코드, | ||
Leetcode, | ||
알고리즘, | ||
array, | ||
dp, | ||
danamic programming, | ||
max, | ||
circular, | ||
circular array, | ||
] | ||
date: 2024-07-03 13:30:00 +0900 | ||
toc: true | ||
--- | ||
|
||
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. | ||
|
||
[https://neetcode.io/practice](https://neetcode.io/practice) | ||
|
||
--- | ||
|
||
[https://leetcode.com/problems/house-robber-ii/](https://leetcode.com/problems/house-robber-ii/) | ||
|
||
바로 전에 풀었던 [House Robber](https://algorithm.jonghoonpark.com/2024/07/03/leetcode-198) 에서 확장된 문제이다. | ||
|
||
원형 array를 사용해서 좀 더 고민을 해줘야 한다. | ||
|
||
포인트는 첫번째 것을 선택하면 마지막 것을 선택하지 못한다는 것이다. | ||
|
||
그래서 다음과 같이 두가지 케이스로 나눠서 계산 한 후 둘 중 더 큰 값을 반환하도록 하였다. | ||
|
||
- 첫번째 부터 n-1 번째까지 | ||
- 두번째 부터 n 번째까지 | ||
|
||
## 내가 작성한 풀이 | ||
|
||
```java | ||
public class Solution { | ||
public int rob(int[] nums) { | ||
if (nums.length == 1) { | ||
return nums[0]; | ||
} | ||
|
||
if (nums.length == 2) { | ||
return Math.max(nums[0], nums[1]); | ||
} | ||
|
||
if (nums.length == 3) { | ||
return Math.max(nums[2], Math.max(nums[0], nums[1])); | ||
} | ||
|
||
|
||
return Math.max(getMaxInRange(nums, 0, nums.length - 1), getMaxInRange(nums, 1, nums.length)); | ||
} | ||
|
||
public int getMaxInRange(int[] nums, int start, int end) { | ||
int[] dp = new int[nums.length]; | ||
int max; | ||
dp[start] = nums[start]; | ||
dp[start + 1] = nums[start + 1]; | ||
dp[start + 2] = nums[start + 2] + nums[start]; | ||
max = Math.max(dp[start + 2], dp[start + 1]); | ||
for (int i = start + 3; i < end; i++) { | ||
dp[i] = Math.max(nums[i] + dp[i - 2], nums[i] + dp[i - 3]); | ||
max = Math.max(max, dp[i]); | ||
} | ||
return max; | ||
} | ||
} | ||
``` | ||
|
||
### TC, SC | ||
|
||
시간 복잡도는 O(n), 공간 복잡도는 O(n) 이다. |