Skip to content

Commit 5b0dfef

Browse files
authored
house robber ii solution
Implement dynamic programming solution for house robber problem.
1 parent 1cab7c9 commit 5b0dfef

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

house-robber-ii/yhkee0404.scala

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
object Solution {
2+
def rob(nums: Array[Int]): Int = {
3+
if (nums.length == 1) {
4+
return nums(0)
5+
}
6+
val dp = Array.fill(nums.length)(Array.fill(2)(0)) // T(n) = S(n) = O(n)
7+
dp(0)(1) = nums(0)
8+
dp(1)(0) = nums(1)
9+
dp(1)(1) = nums(0)
10+
for (i <- 2 until nums.length) {
11+
for (j <- 0 to 1) {
12+
dp(i)(j) = Math.max(dp(i - 1)(j), dp(i - 2)(j) + nums(i))
13+
}
14+
}
15+
Math.max(dp(nums.length - 2)(1), dp(nums.length - 1)(0))
16+
}
17+
}

0 commit comments

Comments
 (0)