kt: add «1352. Product of the Last K Numbers»

URL:	https://leetcode.com/problems/product-of-the-last-k-numbers/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-14 11:44:01 +01:00
parent 84d3480c60
commit e0a3d6a21c
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,22 @@
class ProductOfNumbers() {
private val prefix: MutableList<Int> = mutableListOf(1)
private val size: Int
get() = prefix.size - 1
fun add(num: Int) =
when (num) {
0 -> {
prefix.clear()
prefix.add(1)
}
else -> {
prefix.add(prefix[size] * num)
}
}
fun getProduct(k: Int): Int =
when {
k > size -> 0
else -> prefix[size] / prefix[size - k]
}
}