[LeetCode] Longest Turbulent Subarray

978. Longest Turbulent Subarray

Given an integer array arr, return the length of a maximum size turbulent subarray of arr.

A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

More formally, a subarray [arr[i], arr[i + 1], …, arr[j]] of arr is said to be turbulent if and only if:

  • For i <= k < j:
  • arr[k] > arr[k + 1] when k is odd, and
  • arr[k] < arr[k + 1] when k is even.
  • Or, for i <= k < j:
  • arr[k] > arr[k + 1] when k is even, and
  • arr[k] < arr[k + 1] when k is odd.
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 maxTurbulenceSize(vector<int>& arr) {
int res = 1, n = arr.size();
for(int i = 0, ma1 = 1, ma2 = 1; i < n - 1; i++) {
if(i & 1) {
if(arr[i] > arr[i + 1]) ma1 += 1;
else ma1 = 1;

if(arr[i] < arr[i + 1]) ma2 += 1;
else ma2 = 1;
} else {
if(arr[i] < arr[i + 1]) ma1 += 1;
else ma1 = 1;

if(arr[i] > arr[i + 1]) ma2 += 1;
else ma2 = 1;
}
res = max({res, ma1, ma2});
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/longest-turbulent-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.