|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: (Leetcode) 213 - House Robber ii |
| 4 | +categories: [스터디-알고리즘] |
| 5 | +tags: |
| 6 | + [ |
| 7 | + 자바, |
| 8 | + java, |
| 9 | + 리트코드, |
| 10 | + Leetcode, |
| 11 | + 알고리즘, |
| 12 | + array, |
| 13 | + dp, |
| 14 | + danamic programming, |
| 15 | + max, |
| 16 | + circular, |
| 17 | + circular array, |
| 18 | + ] |
| 19 | +date: 2024-07-03 13:30:00 +0900 |
| 20 | +toc: true |
| 21 | +--- |
| 22 | + |
| 23 | +기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. |
| 24 | + |
| 25 | +[https://neetcode.io/practice](https://neetcode.io/practice) |
| 26 | + |
| 27 | +--- |
| 28 | + |
| 29 | +[https://leetcode.com/problems/house-robber-ii/](https://leetcode.com/problems/house-robber-ii/) |
| 30 | + |
| 31 | +바로 전에 풀었던 [House Robber](https://algorithm.jonghoonpark.com/2024/07/03/leetcode-198) 에서 확장된 문제이다. |
| 32 | + |
| 33 | +원형 array를 사용해서 좀 더 고민을 해줘야 한다. |
| 34 | + |
| 35 | +포인트는 첫번째 것을 선택하면 마지막 것을 선택하지 못한다는 것이다. |
| 36 | + |
| 37 | +그래서 다음과 같이 두가지 케이스로 나눠서 계산 한 후 둘 중 더 큰 값을 반환하도록 하였다. |
| 38 | + |
| 39 | +- 첫번째 부터 n-1 번째까지 |
| 40 | +- 두번째 부터 n 번째까지 |
| 41 | + |
| 42 | +## 내가 작성한 풀이 |
| 43 | + |
| 44 | +```java |
| 45 | +public class Solution { |
| 46 | + public int rob(int[] nums) { |
| 47 | + if (nums.length == 1) { |
| 48 | + return nums[0]; |
| 49 | + } |
| 50 | + |
| 51 | + if (nums.length == 2) { |
| 52 | + return Math.max(nums[0], nums[1]); |
| 53 | + } |
| 54 | + |
| 55 | + if (nums.length == 3) { |
| 56 | + return Math.max(nums[2], Math.max(nums[0], nums[1])); |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | + return Math.max(getMaxInRange(nums, 0, nums.length - 1), getMaxInRange(nums, 1, nums.length)); |
| 61 | + } |
| 62 | + |
| 63 | + public int getMaxInRange(int[] nums, int start, int end) { |
| 64 | + int[] dp = new int[nums.length]; |
| 65 | + int max; |
| 66 | + dp[start] = nums[start]; |
| 67 | + dp[start + 1] = nums[start + 1]; |
| 68 | + dp[start + 2] = nums[start + 2] + nums[start]; |
| 69 | + max = Math.max(dp[start + 2], dp[start + 1]); |
| 70 | + for (int i = start + 3; i < end; i++) { |
| 71 | + dp[i] = Math.max(nums[i] + dp[i - 2], nums[i] + dp[i - 3]); |
| 72 | + max = Math.max(max, dp[i]); |
| 73 | + } |
| 74 | + return max; |
| 75 | + } |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | +### TC, SC |
| 80 | + |
| 81 | +시간 복잡도는 O(n), 공간 복잡도는 O(n) 이다. |
0 commit comments