[Swift]LeetCode978. 最長湍流子數組 | Longest Turbulent Subarray

原文地址:http://www.javashuo.com/article/p-cxqumfgj-md.html html

A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:數組

  • For i <= k < jA[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
  • OR, for i <= k < jA[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.spa

Return the length of a maximum size turbulent subarray of A. code

Example 1:htm

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:blog

Input: [4,8,12,16]
Output: 2 

Example 3:ip

Input: [100]
Output: 1 

Note:element

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

當 A 的子數組 A[i], A[i+1], ..., A[j] 知足下列條件時,咱們稱其爲湍流子數組get

  • 若 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]

也就是說,若是比較符號在子數組中的每一個相鄰元素對之間翻轉,則該子數組是湍流子數組。input

返回 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. 1 <= A.length <= 40000
  2. 0 <= A[i] <= 10^9

676ms

 1 class Solution {
 2     func maxTurbulenceSize(_ A: [Int]) -> Int {
 3         var n:Int = A.count
 4         var dp:Int = 0
 5         var ret:Int = 1
 6         for i in 0..<(n - 1)
 7         {
 8             if A[i] < A[i+1]
 9             {
10                 if i > 0 && A[i-1] > A[i]
11                 {
12                     dp += 1
13                 }
14                 else
15                 {
16                     dp = 2
17                 }
18             }
19             else if A[i] > A[i+1]
20             {
21                 if i > 0 && A[i-1] < A[i]
22                 {
23                     dp += 1
24                 }
25                 else
26                 {
27                     dp = 2
28                 }
29             }
30             else
31             {
32                 dp = 1
33             }
34             ret = max(ret, dp)
35         }
36         return ret        
37     }
38 }
相關文章
相關標籤/搜索