Skip to content

Commit

Permalink
Create 0337-house-robber-iii.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a authored May 25, 2023
1 parent 5ba127b commit cad71db
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions kotlin/0337-house-robber-iii.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun rob(root: TreeNode?): Int {
root?: return 0

val res = rob2(root)
return maxOf(
res.first,
res.second
)
}

fun rob2(root: TreeNode?): Pair<Int, Int> {
root?: return 0 to 0

val left = rob2(root.left)
val right = rob2(root.right)

val with = root.`val` + left.second + right.second
val without = maxOf(left.first, left.second) + maxOf(right.first, right.second)

return with to without
}
}

0 comments on commit cad71db

Please sign in to comment.