# 最长湍流子数组 - Longest Turbulent Subarray

``````当 A 的子数组 A[i], A[i+1], ..., A[j] 满足下列条件时，我们称其为湍流子数组：

``````

### Example:

``````输入：[9,4,2,10,7,8,8,1,9]

``````

``````输入：[4,8,12,16]

``````

``````输入：[100]

``````

1. `1 <= A.length <= 40000`
2. `0 <= A[i] <= 10^9`

## Solutions

### Solution ( 15ms)

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 `````` ``````class Solution { public int maxTurbulenceSize(int[] A) { int length = A.length; if (length == 1) { return 1; } else if (length == 2) { return A[0] == A[1] ? 1 : 2; } int lastCOmpare = Integer.compare(A[0], A[1]); int presentCompare; int maxLength = 0; int curLength = lastCOmpare == 0 ? 1 : 2; for (int i = 1, len = length - 1; i < len; i++) { presentCompare = Integer.compare(A[i], A[i+1]); if (lastCOmpare == 0) { lastCOmpare = presentCompare; curLength = lastCOmpare == 0 ? 1 : 2; continue; } else if (presentCompare == 0) { lastCOmpare = presentCompare; if (curLength > maxLength) { maxLength = curLength; } curLength = 1; } else if (Math.abs(presentCompare + lastCOmpare) == 2) { lastCOmpare = presentCompare; if (curLength > maxLength) { maxLength = curLength; } curLength = 2; } else { lastCOmpare = presentCompare; curLength++; } } if (curLength > maxLength) { maxLength = curLength; } return maxLength; } } ``````

### Solution ( 22ms)

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 `````` ``````class Solution { public int maxTurbulenceSize(int[] A) { int N = A.length; int ans = 1; int anchor = 0; for (int i = 1; i < N; ++i) { int c = Integer.compare(A[i-1], A[i]); if (i == N-1 || c * Integer.compare(A[i], A[i+1]) != -1) { if (c != 0) ans = Math.max(ans, i - anchor + 1); anchor = i; } } return ans; } } ``````

## Solution (11ms)

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 `````` ``````class Solution { public int maxTurbulenceSize(int[] A) { if (A.length == 1) return 1; int[] o = new int[A.length-1]; for (int i = 0; i < A.length - 1; ++i) { if (A[i + 1] - A[i] > 0) { o[i]=1; } else if (A[i + 1] - A[i] < 0) { o[i]=-1; } else { o[i]=0; } } int count=0; int maxCount=0; for(int i=0;i