978. The longest turbulence subarray
When the A
sub-array A[i], A[i+1], ..., A[j]
when the following conditions are met, we call it turbulent sub-array:
- If
i <= k < j
, whenk
an odd number,A[k] > A[k+1]
and whenk
an evenA[k] < A[k+1]
number, ; - Or, if
i <= k < j
, whenk
an even number,A[k] > A[k+1]
and whenk
an oddA[k] < A[k+1]
number, .
That is, if the comparison sign flips between each pair of adjacent elements in the sub-array, the sub-array is a turbulent sub-array.
Returns the A
maximum length of the subarray of turbulence.
Example 1:
输入:[9,4,2,10,7,8,8,1,9]
输出:5
解释:(A[1] > A[2] < A[3] > A[4] < A[5])
Example 2:
输入:[4,8,12,16]
输出:2
Example 3:
输入:[100]
输出:1
prompt:
1 <= A.length <= 40000
0 <= A[i] <= 10^9
Method One: Strong Lu
Problem-solving ideas
- No special skills, traverse the array once, compare the numbers one by one, and find out the length of the sub-array
Reference Code
public int maxTurbulenceSize(int[] arr) {
int n = arr.length, idx = 0;
int ret = 1, preState = 0;
for (int i = 1; i < n; i++) {
int state = Integer.compare(arr[i], arr[i - 1]);
if (state == preState || state == 0) {
ret = Math.max(ret, i - idx);
idx = state == 0 ? i : i - 1;
}
preState = state;
}
return Math.max(ret, n - idx);
}
Results of the
Method two: dynamic programming
Problem-solving ideas
- State definition: each corner is marked with three states, namely uphill, downhill, and flat (equal to the previous number)
up[i]
It denotes the index ofi
a sub-array length during uphilldown[i]
Denotes the index ofi
a sub-array when the length downhill- If it is flat, then
down[i] = up[i] = 1
- Initialization: Let the two arrays be all
1
. - State transition:
- Index
i
is uphill:up[i] = down[i] + 1
- Index
i
downhill:down[i] = up[i] + 1
- Index
i
is flat, do not do anything (can not initialize, so heredown[i] = up[i] = 1
)
- Index
Reference Code
public int maxTurbulenceSize(int[] arr) {
int n = arr.length;
int[] up = new int[n], down = new int[n];
Arrays.fill(up, 1);
Arrays.fill(down, 1);
int ret = 1;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1]) {
up[i] = down[i - 1] + 1;
} else if(arr[i] < arr[i - 1]) {
down[i] = up[i - 1] + 1;
}
ret = Math.max(ret, Math.max(up[i], down[i]));
}
return ret;
}
Results of the