978. Longest Turbulent Subarray
Solution
紀錄上一個wave的狀態 (up/down/even)。
然後比較這次狀態,並進行count的變化
public int maxTurbulenceSize(int[] A) {
if(A.length <= 1) return A.length;
int flag = 0; // 0: equal, 1 : up, -1 : down
int count = 1;
int max = 1;
for(int i = 1; i < A.length; i++){
if(A[i] > A[i-1]){
if(flag == -1){
count++;
}
else{
count = 2;
}
flag = 1;
}
else if (A[i] < A[i-1]){
if(flag == 1){
count++;
}
else{
count = 2;
}
flag = -1;
}
else{
flag = 0;
count = 1;
}
max = Math.max(max, count);
}
return max;
}
Last updated
Was this helpful?