-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0198-house-robber.kt
54 lines (45 loc) · 1.09 KB
/
0198-house-robber.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
// DP Time O(n) and Space O(1)
class Solution {
fun rob(nums: IntArray): Int {
var rob = 0
var notRob = 0
nums.forEach {
val currRob = notRob + it
notRob = maxOf(notRob, rob)
rob = currRob
}
return maxOf(rob, notRob)
}
}
// DP Time O(n) and Space O(n)
class Solution {
fun rob(nums: IntArray): Int {
val n = nums.size
val dp = IntArray (n)
dp[0] = nums[0]
for (i in 1 until n) {
dp[i] = maxOf(
nums[i] + if (i > 1) dp[i - 2] else 0,
dp[i - 1]
)
}
return dp[n - 1]
}
}
// Recursion + memoization Time O(n) and Space O(n)
class Solution {
fun rob(nums: IntArray): Int {
val n = nums.size
val dp = IntArray (n) { -1 }
fun dfs(i: Int): Int {
if (i >= n) return 0
if (dp[i] != -1) return dp[i]
dp[i] = maxOf(
nums[i] + dfs(i + 2),
dfs(i + 1)
)
return dp[i]
}
return dfs(0)
}
}