File tree Expand file tree Collapse file tree 1 file changed +43
-2
lines changed Expand file tree Collapse file tree 1 file changed +43
-2
lines changed Original file line number Diff line number Diff line change 1+ // DP Time O(n) and Space O(1)
12class Solution {
2- fun rob (nums : IntArray ): Int {
3+ fun rob (nums : IntArray ): Int {
34 var rob = 0
45 var notRob = 0
56 nums.forEach {
@@ -10,4 +11,44 @@ class Solution {
1011
1112 return maxOf(rob, notRob)
1213 }
13- }
14+ }
15+
16+ // DP Time O(n) and Space O(n)
17+ class Solution {
18+ fun rob (nums : IntArray ): Int {
19+ val n = nums.size
20+ val dp = IntArray (n)
21+ dp[0 ] = nums[0 ]
22+
23+ for (i in 1 until n) {
24+ dp[i] = maxOf(
25+ nums[i] + if (i > 1 ) dp[i - 2 ] else 0 ,
26+ dp[i - 1 ]
27+ )
28+ }
29+
30+ return dp[n - 1 ]
31+ }
32+ }
33+
34+ // Recursion + memoization Time O(n) and Space O(n)
35+ class Solution {
36+ fun rob (nums : IntArray ): Int {
37+ val n = nums.size
38+ val dp = IntArray (n) { - 1 }
39+
40+ fun dfs (i : Int ): Int {
41+ if (i >= n) return 0
42+ if (dp[i] != - 1 ) return dp[i]
43+
44+ dp[i] = maxOf(
45+ nums[i] + dfs(i + 2 ),
46+ dfs(i + 1 )
47+ )
48+
49+ return dp[i]
50+ }
51+
52+ return dfs(0 )
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments