#2765

Longest Alternating Subarray

pupil · 545 · lc easy +28 · 35.1% accepted · 245 likes · top 13%

Description

Consider a 0-indexed integer array nums. A subarray s of length m is called alternating provided all of these conditions hold:

- m is greater than 1.

- s1 = s0 + 1.

- The pattern of s is [s0, s1, s0, s1,...,s(m-1) % 2]: each successive difference alternates between 1 and -1, ending with s[m - 1] - s[m - 2] = (-1)m.

Find and return the maximum length among all alternating subarrays of nums, or -1 if no such subarray exists.

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

Code

1
2
3