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:
parent
84d3480c60
commit
e0a3d6a21c
1 changed files with 22 additions and 0 deletions
22
kt/product-of-the-last-k-numbers.kt
Normal file
22
kt/product-of-the-last-k-numbers.kt
Normal 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]
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue