Description
You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if:
mis greater than1.s1 = s0 + 1.- The 0-indexed subarray
slooks like[s0, s1, s0, s1,...,s(m-1) % 2]. In other words,s1 - s0 = 1,s2 - s1 = -1,s3 - s2 = 1,s4 - s3 = -1, and so on up tos[m - 1] - s[m - 2] = (-1)m.
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 [2, 3], [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:
2 <= nums.length <= 1001 <= nums[i] <= 104
Solution
Python3
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
N = len(nums)
res = -1
for i in range(N):
prev = nums[i]
inc = True
for j in range(i + 1, N):
target = prev + 1 if inc else prev - 1
if nums[j] != target:
break
prev = nums[j]
inc = not inc
res = max(res, j - i + 1)
return res