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:
parent
7f84417da5
commit
2b57831852
1 changed files with 32 additions and 0 deletions
32
kt/number-of-sub-arrays-with-odd-sum.kt
Normal file
32
kt/number-of-sub-arrays-with-odd-sum.kt
Normal 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
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue