Skip to content

Commit

Permalink
Add scala solution for 213-House-Robber-II
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisKheng committed Sep 25, 2022
1 parent 918d008 commit c1f5021
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions scala/213-House-Robber-II.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
object Solution {
def rob(nums: Array[Int]): Int = {
if (nums.length == 1) {
return nums(0)
} else {
return houseRobber1(nums, 0, nums.length - 2).max(houseRobber1(nums, 1, nums.length - 1))
}
}

def houseRobber1(nums: Array[Int], start: Int, end: Int): Int = {
var (prevMaxProfit, prevTwoMaxProfit) = (0, 0)

for (i <- start to end) {
val profit = (nums(i) + prevTwoMaxProfit).max(prevMaxProfit)
prevTwoMaxProfit = prevMaxProfit
prevMaxProfit = profit
}

return prevMaxProfit
}
}

0 comments on commit c1f5021

Please sign in to comment.