刷题-力扣-987
978. 最长湍流子数组
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-turbulent-subarray/
作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
当 A 的子数组 A[i], A[i+1], ..., A[j] 满足下列条件时,我们称其为湍流子数组:
若 i <= k < j,当 k 为奇数时, A[k] > A[k+1],且当 k 为偶数时,A[k] < A[k+1];
或 若 i <= k < j,当 k 为偶数时,A[k] > A[k+1] ,且当 k 为奇数时, A[k] < A[k+1]。
也就是说,如果比较符号在子数组中的每个相邻元素对之间翻转,则该子数组是湍流子数组。
返回 A 的最大湍流子数组的长度。
示例 1:
输入:[9,4,2,10,7,8,8,1,9]
输出:5
解释:(A[1] > A[2] < A[3] > A[4] < A[5])
示例 2:
输入:[4,8,12,16]
输出:2
示例 3:
输入:[100]
输出:1
提示:
- 1 <= A.length <= 40000
- 0 <= A[i] <= 10^9
题目分析
- 根据题目描述要求前第一个数字大于(或小于)第二个数字,第二个数字小于(或大于)下一个数字,依次类推,即为湍流字串
- 创建两个变量upLen和downLen保存两种情况下的湍流字串长度,当湍流终止时,记录最大长度到maxLen中
- 遍历结束后maxLen即为所求
代码
class Solution {
public:
int maxTurbulenceSize(vector<int>& arr) {
int maxLen = 0;
int upLen = 1;
int downLen = 1;
for (int i = 0; i < arr.size() - 1; i++) {
if (i % 2 == 1) {
if (arr[i] > arr[i + 1]) {
upLen++;
maxLen = maxLen > downLen ? maxLen : downLen;
downLen = 1;
}
else if (arr[i] < arr[i + 1]) {
downLen++;
maxLen = maxLen > upLen ? maxLen : upLen;
upLen = 1;
}
else {
maxLen = maxLen > upLen ? maxLen : upLen;
upLen = 1;
maxLen = maxLen > downLen ? maxLen : downLen;
downLen = 1;
}
}
else {
if (arr[i] < arr[i + 1]) {
upLen++;
maxLen = maxLen > downLen ? maxLen : downLen;
downLen = 1;
}
else if (arr[i] > arr[i + 1]) {
downLen++;
maxLen = maxLen > upLen ? maxLen : upLen;
upLen = 1;
}
else {
maxLen = maxLen > upLen ? maxLen : upLen;
upLen = 1;
maxLen = maxLen > downLen ? maxLen : downLen;
downLen = 1;
}
}
}
maxLen = maxLen > upLen ? maxLen : upLen;
maxLen = maxLen > downLen ? maxLen : downLen;
return maxLen;
}
};