|
| 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