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 allalternating subarrays present in _numsor-1if no such subarray exists.
A subarray is a contiguous non-empty sequence of elements within an array.
Input: nums =[2,3,4,3,4]Output: 4Explanation:
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.
We look for the longest subarray where the elements alternate between two values differing by 1, starting with s0 and s1 = s0 + 1. We can check each possible starting point and expand as long as the alternating pattern holds.
classSolution {
public:int alternatingSubarray(vector<int>& nums) {
int n = nums.size(), ans =-1;
for (int i =0; i < n-1; ++i) {
if (nums[i+1] != nums[i]+1) continue;
int len =2, j = i+2, sign =-1;
while (j < n && nums[j] - nums[j-1] == sign) {
len++;
sign *=-1;
j++;
}
ans = max(ans, len);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
funcalternatingSubarray(nums []int) int {
n, ans:= len(nums), -1fori:=0; i < n-1; i++ {
ifnums[i+1] !=nums[i]+1 {
continue }
l, j, sign:=2, i+2, -1forj < n&&nums[j]-nums[j-1] ==sign {
l++sign*=-1j++ }
ifl > ans {
ans = l }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintalternatingSubarray(int[] nums) {
int n = nums.length, ans =-1;
for (int i = 0; i < n-1; i++) {
if (nums[i+1]!= nums[i]+1) continue;
int len = 2, j = i+2, sign =-1;
while (j < n && nums[j]- nums[j-1]== sign) {
len++;
sign *=-1;
j++;
}
ans = Math.max(ans, len);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funalternatingSubarray(nums: IntArray): Int {
val n = nums.size
var ans = -1for (i in0 until n-1) {
if (nums[i+1] != nums[i]+1) continuevar len = 2var j = i+2var sign = -1while (j < n && nums[j] - nums[j-1] == sign) {
len++ sign *= -1 j++ }
ans = maxOf(ans, len)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defalternatingSubarray(self, nums: list[int]) -> int:
n = len(nums)
ans =-1for i in range(n-1):
if nums[i+1] != nums[i]+1:
continue l, j, sign =2, i+2, -1while j < n and nums[j] - nums[j-1] == sign:
l +=1 sign *=-1 j +=1 ans = max(ans, l)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnalternating_subarray(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans =-1;
for i in0..n-1 {
if nums[i+1] != nums[i]+1 { continue; }
letmut len =2;
letmut j = i+2;
letmut sign =-1;
while j < n && nums[j] - nums[j-1] == sign {
len +=1;
sign *=-1;
j +=1;
}
ans = ans.max(len);
}
ans
}
}