|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | +import kotlin.math.max |
| 6 | + |
| 7 | +class `house-robber` { |
| 8 | + |
| 9 | + fun rob(nums: IntArray): Int { |
| 10 | + return usingDP(nums) |
| 11 | + } |
| 12 | + |
| 13 | + /** |
| 14 | + * TC: O(n), SC: O(n) |
| 15 | + */ |
| 16 | + private fun usingDP(nums: IntArray): Int { |
| 17 | + val dp = IntArray(nums.size + 1).apply { |
| 18 | + this[0] = 0 |
| 19 | + this[1] = nums[0] |
| 20 | + } |
| 21 | + for (index in 1 until nums.size) { |
| 22 | + dp[index + 1] = max(nums[index] + dp[index - 1], dp[index]) |
| 23 | + } |
| 24 | + |
| 25 | + return dp[nums.size] |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * TC: O(n), SC: O(n) |
| 30 | + */ |
| 31 | + private fun usingMemoization(nums: IntArray): Int { |
| 32 | + val memo = IntArray(nums.size) { -1 } |
| 33 | + fun recursive(index: Int): Int { |
| 34 | + return if (index > nums.size - 1) 0 |
| 35 | + else if (memo[index] != -1) memo[index] |
| 36 | + else { |
| 37 | + memo[index] = max(nums[index] + recursive(index + 2), recursive(index + 1)) |
| 38 | + memo[index] |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return recursive(0) |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * 시간초과 |
| 47 | + * TC: O(2^n), SC: O(n) |
| 48 | + */ |
| 49 | + private fun usingRecursive(nums:IntArray): Int { |
| 50 | + fun recursive(index: Int, depth: Int): Int { |
| 51 | + if (index > nums.size - 1) return 0 |
| 52 | + println("${"-".repeat(depth)} : max($index + ${index + 2}, ${index + 1})") |
| 53 | + return max(nums[index] + recursive(index + 2, depth + 1), recursive(index + 1, depth + 1)) |
| 54 | + } |
| 55 | + |
| 56 | + return recursive(0, 0) |
| 57 | + } |
| 58 | + |
| 59 | + @Test |
| 60 | + fun `인접하지 않은 원소를 선택하여 최대의 합을 반환한다`() { |
| 61 | + rob(intArrayOf(1,2,3,1)) shouldBe 4 |
| 62 | + rob(intArrayOf(2,7,9,3,1)) shouldBe 12 |
| 63 | + rob(intArrayOf(8,7,9,11,1)) shouldBe 19 |
| 64 | + } |
| 65 | +} |
0 commit comments