0%

Longest Turbulent Subarray

Question

A subarray A[i], A[i+1], …, A[j] of A is said to be turbulent if and only if:

For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.
That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

Return the length of a maximum size turbulent subarray of A.

Example 1:
Input: [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])

Solution

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
/*
@param: int[] input numbers
@return: int, max length of turbulent subarray;
Algorithm: 使用两个状态量up, down,如果当前
A[i] > A[i-1], 则 up = down+1; down = 1;
A[i] < A[i-1], 则 down = up+1; up = 1;
反之 up, down = 1;
巧妙的以结果判断来保留状态量的值。
*/
public int maxTurbulenceSize(int[] A) {
if (A.length <= 1) {
return A.length;
}
int up = 1, down = 1;
int max = 1;

for (int i = 1; i < A.length; i++) {
if (A[i] > A[i-1]) {
up = down+1;
down = 1;
}else if (A[i] < A[i-1]) {
down = up+1;
up = 1;
}else {
down = 1;
up = 1;
}
max = Math.max(max, Math.max(up, down));
}
return max;
}