[LeetCode] Longest Alternating Subarray

2765. Longest Alternating Subarray

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

  • m is greater than 1.
  • s1 = s0 + 1.
  • The 0-indexed subarray s looks 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 to s[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int alternatingSubarray(vector<int>& nums) {
int res = -1, l = 0, r = 0, n = nums.size();
while(l < n) {
if(l + 1 < n and nums[l] + 1 == nums[l + 1]) {
int a = nums[l], b = nums[l+1], cnt = 0;
while(l < n) {
if(nums[l] == a) cnt += 1;
else break;
swap(a,b);
l += 1;
}
res = max(res, cnt);
l -= 1;
} else l += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/09/PS/LeetCode/longest-alternating-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.