Leetcode 978
问题描述
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])
Example 2:
Input: [4,8,12,16]
Output: 2
Example 3:
Input: [100]
Output: 1
方法一
** Solution Java **
** 4ms, 95.62% **
** 43.5MB, 62.50% **
class Solution {
public int maxTurbulenceSize(int[] A) {
int dec = 1, inc = 1, res = 1;
for (int i = 1; i < A.length; ++i) {
if (A[i - 1] < A[i]) {
inc = dec + 1;
dec = 1;
} else if (A[i] < A[i - 1]){
dec = inc + 1;
inc = 1;
} else {
inc = 1;
dec = 1;
}
res = Math.max(res, Math.max(dec, inc));
}
return res;
}
}
方法二
** Solution Java **
** 4ms, 95.62% **
** 43.2MB, 62.50% **
class Solution {
public int maxTurbulenceSize(int[] A) {
int pre = 0, cur = 0, len = 1, res = 1;
for (int i = 1; i < A.length; ++i) {
cur = Integer.compare(A[i], A[i - 1]);
if (cur * pre == -1) ++len;
else if (cur == 0) len = 1;
else len = 2;
res = Math.max(res, len);
pre = cur;
}
return res;
}
}