LeetCode in Kotlin

3101. Count Alternating Subarrays

Medium

You are given a binary array nums.

We call a subarray alternating if no two adjacent elements in the subarray have the same value.

Return the number of alternating subarrays in nums.

Example 1:

Input: nums = [0,1,1,1]

Output: 5

Explanation:

The following subarrays are alternating: [0], [1], [1], [1], and [0,1].

Example 2:

Input: nums = [1,0,1,0]

Output: 10

Explanation:

Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.

Constraints:

Solution

class Solution {
    fun countAlternatingSubarrays(nums: IntArray): Long {
        var count: Long = 0
        var length: Long
        var start = 0
        var end = 1
        while (end < nums.size) {
            if (nums[end] != nums[end - 1]) {
                end++
            } else {
                length = end - start.toLong()
                count += (length * (length + 1)) / 2
                start = end
                end++
            }
        }
        length = end - start.toLong()
        count += (length * (length + 1)) / 2
        return count
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy