2765. Longest Alternating Subarray

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int alternatingSubarray(int[] nums) {
int maxLength = -1;

for (int i = 0; i < nums.length - 1; ) { // 枚举起点
if (nums[i] + 1 == nums[i + 1]) {
// 可作为交替子数组开头,尝试向右扩张
int j = i + 2;
int exceptedDiff = -1;
while (j < nums.length && nums[j] == nums[j - 1] + exceptedDiff) {
exceptedDiff *= -1;
j++;
}
// now: [i, j)
maxLength = Math.max(maxLength, j - i);
i = j - 1; // 注意此处需要从 j - 1 从新开始尝试,如数组 [1, 2, 3, 2], 其中的最长交替子数组为 [2, 3, 2]
} else {
i++;
}
}

return maxLength;
}
}

References

2765. Longest Alternating Subarray