Leetcode978. Longest Turbulent Subarray

给定一个数组,找到最长的turbulent子数组的长度

turbulent子数组就是一增一减交替

其实这题也很简单,就是直接找子数组,不满足条件了,就重新开始算

class Solution {
public:
    int maxTurbulenceSize(vector<int>& arr) {
        int ans = 1, n = arr.size(), cur = 1;
        int state = 0;
        for(int i = 1; i < n; ++i){
            if(arr[i] == arr[i - 1]){
                state = 0;
                cur = 1;
            }
            else if(arr[i - 1] < arr[i]){
                if(state == -1){
                    ++cur;
                }
                else{
                    cur = 2;
                }
                ans = max(cur, ans);
                state = 1;
            }
            else{
                if(state == 1){
                    ++cur;
                }
                else{
                    cur = 2;
                }
                ans = max(cur, ans);
                state = -1;
            }
        }
        return ans;
    }
};

时间复杂度 O ( n ) O(n) O(n)

你可能感兴趣的:(数据结构与算法,算法,数据结构,leetcode)