LeetCode in Kotlin

2765. Longest Alternating Subarray

Easy

You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if:

Return the maximum length of all alternating subarrays present in nums or -1 if no such subarray exists__.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [2,3,4,3,4]

Output: 4

Explanation: The alternating subarrays are [3,4], [3,4,3], and [3,4,3,4]. The longest of these is [3,4,3,4], which is of length 4.

Example 2:

Input: nums = [4,5,6]

Output: 2

Explanation: [4,5] and [5,6] are the only two alternating subarrays. They are both of length 2.

Constraints:

Solution

import kotlin.math.abs

class Solution {
    fun alternatingSubarray(nums: IntArray): Int {
        var result = -1
        var prious = 0
        var sum = 1
        for (i in 1..nums.lastIndex) {
            val s = nums[i] - nums[i - 1]
            if (abs(s) != 1) {
                sum = 1
                continue
            }
            if (s == prious) {
                sum = 2
            }
            if (s != prious) {
                if (s != if (sum % 2 == 0) -1 else 1) continue
                sum++
                prious = s
            }
            result = maxOf(result, sum)
        }
        return result
    }
}