URL: https://leetcode.com/problems/longest-nice-subarray/ Signed-off-by: Matej Focko <me@mfocko.xyz>
26 lines
731 B
Kotlin
26 lines
731 B
Kotlin
class Solution {
|
|
private data class Acc(var used: Int, var start: Int, val max: Int) {
|
|
constructor() : this(0, 0, 0)
|
|
|
|
fun update(
|
|
nums: IntArray,
|
|
end: IndexedValue<Int>,
|
|
): Acc {
|
|
// shrink from left until conflict gets resolved
|
|
while (used.and(end.value) != 0) {
|
|
used = used.xor(nums[start])
|
|
++start
|
|
}
|
|
|
|
return copy(
|
|
used = used.or(end.value),
|
|
max = maxOf(max, end.index - start + 1),
|
|
)
|
|
}
|
|
}
|
|
|
|
fun longestNiceSubarray(nums: IntArray): Int =
|
|
nums.withIndex().fold(Acc()) { acc, end ->
|
|
acc.update(nums, end)
|
|
}.max
|
|
}
|