kt: add «1524. Number of Sub-arrays With Odd Sum»

URL:	https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-25 15:41:11 +01:00
parent 7f84417da5
commit 2b57831852
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,32 @@
class Solution {
companion object {
private val MOD: Int = 1_000_000_007
}
private data class Acc(val count: Int, val sum: Int, val odd: Int, val even: Int) {
constructor() : this(0, 0, 0, 1) {}
fun update(num: Int): Acc =
(sum + num).let { sum ->
when {
sum % 2 == 0 ->
this.copy(
count = (count + odd) % MOD,
sum = sum,
even = even + 1,
)
else ->
this.copy(
count = (count + even) % MOD,
sum = sum,
odd = odd + 1,
)
}
}
}
fun numOfSubarrays(arr: IntArray): Int =
arr.fold(Acc()) { acc, it ->
acc.update(it)
}.count
}