[leetcode] 978. Longest Turbulent Subarray

Description

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

Note:

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

分析

题目的意思是:这道题要求我们找出最长的震荡子序列,我想过要暴力破解啥的,当我写完了之后我就感觉完了,要分两种情况来做,还是双循环,肯定会超时。看了一下参考答案,可以用滑动窗口来做,把数组A标成1,0,-1的情况,然后用乘法就可以判断相邻两个数是否是一个大一个小,这样的话就不用分两种情况判断了,大概思路就是这样例如:

A = [9,4,2,10,7,8,8,1,9]
把它标注成:[1,1,-1,1,-1,0,-1,1]
满足条件的子数组:[1], [1,-1,1,-1], [0], [-1,1]

这样就只需要遍历一遍就行了

代码

class Solution:
    def compare(self,a,b):
        if(a>b):
            return 1
        elif(a int:
        N=len(A)
        res=1
        anchor=0
        for i in range(1,N):
            c=self.compare(A[i-1],A[i])
            if(c==0):
                anchor=i
            elif(i==N-1 or c*self.compare(A[i],A[i+1])!=-1):
                res=max(res,i-anchor+1)
                anchor=i
        return res

参考文献

[LeetCode] Approach 1: Sliding Window

你可能感兴趣的:(python,leetcode题解)