Skip to content

978. Longest Turbulent Subarray 👍

  • Time: $O(n)$
  • Space: $O(1)$
 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 ans = 1;
    int increasing = 1;
    int decreasing = 1;

    for (int i = 1; i < arr.size(); ++i) {
      if (arr[i] > arr[i - 1]) {
        increasing = decreasing + 1;
        decreasing = 1;
      } else if (arr[i] < arr[i - 1]) {
        decreasing = increasing + 1;
        increasing = 1;
      } else {
        increasing = 1;
        decreasing = 1;
      }
      ans = max({ans, increasing, decreasing});
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int maxTurbulenceSize(int[] arr) {
    int ans = 1;
    int increasing = 1;
    int decreasing = 1;

    for (int i = 1; i < arr.length; ++i) {
      if (arr[i] > arr[i - 1]) {
        increasing = decreasing + 1;
        decreasing = 1;
      } else if (arr[i] < arr[i - 1]) {
        decreasing = increasing + 1;
        increasing = 1;
      } else {
        increasing = 1;
        decreasing = 1;
      }
      ans = Math.max(ans, Math.max(increasing, decreasing));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def maxTurbulenceSize(self, arr: list[int]) -> int:
    ans = 1
    increasing = 1
    decreasing = 1

    for i in range(1, len(arr)):
      if arr[i] > arr[i - 1]:
        increasing = decreasing + 1
        decreasing = 1
      elif arr[i] < arr[i - 1]:
        decreasing = increasing + 1
        increasing = 1
      else:
        increasing = 1
        decreasing = 1
      ans = max(ans, max(increasing, decreasing))

    return ans