978. 最长湍流子数组

Difficulty: 中等

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:

1
2
3
输入:[9,4,2,10,7,8,8,1,9]
输出:5
解释:(A[1] > A[2] < A[3] > A[4] < A[5])

示例 2:

1
2
输入:[4,8,12,16]
输出:2

示例 3:

1
2
输入:[100]
输出:1

提示:

  1. 1 <= A.length <= 40000
  2. 0 <= A[i] <= 10^9

Solution

Language: ****

我的解题代码

 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
class Solution {
public:
    int maxTurbulenceSize(vector<int>& arr) {
        return calc(arr);
    }
    int calc(vector<int> &nums ) {
        int n = nums.size();
        vector<int> down(n,1);
        vector<int> up(n,1);
        int ans = 1;
        for(int i=1;i<n;++i) {
            if(nums[i] > nums[i-1]) {
                down[i] = 1;
                up[i] = down[i-1] + 1;
            }else if(nums[i] < nums[i-1]) {
                down[i] = up[i-1] + 1;
                up[i] = 1;
            }else {
                up[i] = down[i] = 1;
            }
            ans = max(ans, max(up[i] , down[i]));
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    int maxTurbulenceSize(vector<int>& A) {
        vector<vector<int>> dp(A.size(), vector<int>(2,1));
        int ans = 1;
        for(int i = 1; i < A.size(); ++i){
            if(A[i] > A[i-1]){
                dp[i][0] = dp[i-1][1] + 1;
            }else if(A[i] < A[i-1]){
                dp[i][1] = dp[i-1][0] + 1;
            }else{
                continue;
            }
            ans = max(ans, max(dp[i][1], dp[i][0]));
        }
        return ans;
    }
};