-
Notifications
You must be signed in to change notification settings - Fork 8
/
Solution.kt
68 lines (58 loc) · 1.62 KB
/
Solution.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Created by Inno Fang on 2017/12/7.
*/
// 198
class Solution {
var memo: MutableList<Int> = MutableList(0) { -1 }
fun rob(nums: IntArray): Int {
memo.addAll(MutableList(nums.size) { -1 })
return tryRob(nums, 0)
}
private fun tryRob(nums: IntArray, index: Int): Int {
if (index >= nums.size)
return 0
if (memo[index] != -1)
return memo[index]
var res = 0
(index until nums.size).forEach {
res = maxOf(res, nums[it] + tryRob(nums, it + 2))
}
memo[index] = res
return res
}
}
class Solution2 {
fun rob(nums: IntArray): Int {
val n = nums.size
if (n == 0) return 0
val dp = Array(n) { -1 }
dp[n - 1] = nums[n - 1]
(n - 2 downTo 0).forEach { i ->
(i until n).forEach { j ->
dp[i] = maxOf(dp[i], nums[j] + (if (j + 2 < n) dp[j + 2] else 0))
}
}
return dp[0]
}
}
public class Solution3 {
fun rob(nums: IntArray): Int {
if (nums.isEmpty()) return 0
val n = nums.size
val dp = Array(nums.size) { -1 }
dp[0] = nums[0]
(1 until n).forEach { i ->
dp[i] = maxOf(dp[i - 1], nums[i] + if (i > 1) dp[i - 2] else 0)
}
// dp.forEach(::println)
return dp[n - 1]
}
}
fun main(args: Array<String>) {
val solution = Solution3()
solution.rob(intArrayOf(3, 4, 2, 1)).let(::println)
solution.rob(intArrayOf(8, 4, 5, 3, 1)).let(::println)
}
// 213. House Robber II
// 337. House Robber III
// 309. Best Time to Buy and Sell Stock with Cooldown