|
| 1 | +/* |
| 2 | +[문제풀이] |
| 3 | +(X) 주어진 nums 배열에서 index 홀수의 합과 짝수의 합을 비교해보자. |
| 4 | + class Solution { |
| 5 | + public int rob(int[] nums) { |
| 6 | + if (nums.length == 1) { |
| 7 | + return nums[0]; |
| 8 | + } |
| 9 | +
|
| 10 | + for (int i = 1; i <= nums.length; i++) { |
| 11 | + int beforeStepIndex = i - 2; |
| 12 | + if (beforeStepIndex >= 1) { |
| 13 | + nums[i - 1] += nums[beforeStepIndex - 1]; |
| 14 | + } |
| 15 | + } |
| 16 | + return Math.max(nums[nums.length - 1], nums[nums.length - 2]); |
| 17 | + } |
| 18 | + } |
| 19 | + >> 바로 옆이 아니어도 된다. |
| 20 | +
|
| 21 | +(O) 현재 num과 이전 num을 비교하여, 큰 값을 기준으로 더한다. |
| 22 | +time: O(N), space: O(1) |
| 23 | + class Solution { |
| 24 | + public int rob(int[] nums) { |
| 25 | + int prevNum = 0; |
| 26 | + int sum = 0; |
| 27 | + for (int num : nums) { |
| 28 | + int temp = Math.max(sum, prevNum + num); |
| 29 | + prevNum = sum; |
| 30 | + sum = temp; |
| 31 | + } |
| 32 | + return sum; |
| 33 | + } |
| 34 | + } |
| 35 | + >> 공간복잡도 최적화 솔루션으로, dp 보다 직관적이지 않아, 메모리 사용이 제한되거나 입력 크기가 매우 클 때 사용하는 것이 좋을 듯 |
| 36 | +
|
| 37 | +time: O(N), space: O(N) |
| 38 | + class Solution { |
| 39 | + public int rob(int[] nums) { |
| 40 | + if (nums.length == 1) { |
| 41 | + return nums[0]; |
| 42 | + } |
| 43 | +
|
| 44 | + int[] dp = new int[nums.length]; |
| 45 | + dp[0] = nums[0]; |
| 46 | + dp[1] = Math.max(nums[0], nums[1]); |
| 47 | +
|
| 48 | + for (int i = 2; i < nums.length; i++) { |
| 49 | + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); |
| 50 | + } |
| 51 | + return dp[nums.length - 1]; |
| 52 | + } |
| 53 | + } |
| 54 | + >> 공간복잡도는 좀 더 높지만, 직관적이다. |
| 55 | +[회고] |
| 56 | +개발은 혼자하는 것이 아니기도 하고, 디버깅하기 쉽게 직관적인 DP로 푸는게 좋지 않을까?..? |
| 57 | +*/ |
| 58 | +class Solution { |
| 59 | + public int rob(int[] nums) { |
| 60 | + if (nums.length == 1) { |
| 61 | + return nums[0]; |
| 62 | + } |
| 63 | + |
| 64 | + int[] dp = new int[nums.length]; |
| 65 | + dp[0] = nums[0]; |
| 66 | + dp[1] = Math.max(nums[0], nums[1]); |
| 67 | + |
| 68 | + for (int i = 2; i < nums.length; i++) { |
| 69 | + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); |
| 70 | + } |
| 71 | + return dp[nums.length - 1]; |
| 72 | + } |
| 73 | +} |
0 commit comments