kt: add «198. House Robber»

URL:	https://leetcode.com/problems/house-robber/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-06 22:06:39 +01:00
parent 676b7e2262
commit 734cb7d959
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

23
kt/house-robber.kt Normal file
View file

@ -0,0 +1,23 @@
class Solution {
private fun get(
nums: IntArray,
i: Int,
): Int =
when {
i < 0 -> 0
i >= nums.size -> 0
else -> nums[i]
}
fun rob(nums: IntArray): Int =
when (nums.size) {
0 -> 0
else -> {
nums.indices.drop(1).forEach { i ->
nums[i] = listOf(nums[i - 1], get(nums, i - 2) + nums[i]).max()
}
nums.last()
}
}
}