978. Longest Turbulent Subarray
In: arr
Out: 最長turbulent subarray
符合條件1或是條件2即是turbulent.
條件1:
arr 中奇數位置(前)的值要比偶數位置(後)的值大
arr 中偶數位置(前)的值要比奇數位置(後)的值小
Or
條件2:
arr 中偶數位置(前)的值要比奇數位置(後)的值大
arr 中奇數位置(前)的值要比偶數位置(後)的值小
A subarray is a contiguous part of array.
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
c1 = 1
c2 = 1
c1_max = (-1)
c2_max = (-1)
if len(arr)==1:
return 1
status = (-1)
for i in range(len(arr)-1):
print("i-Status:",i,status)
print("c1_max:",c1_max)
print("c2_max:",c2_max)
# if is even
if i%2==0:
if arr[i]>arr[i+1]:
if status==2 or status==(-1):
c2+=1
status = 2
else:
c2+=1
c1 = 1
status = (2)
if c1 > c1_max and status==1:
c1_max = c1
if c2 > c2_max and status==2:
c2_max = c2
elif arr[i]<arr[i+1]:
if status==1 or status==(-1):
c1+=1
status = 1
else:
c1+=1
c2 = 1
status = (1)
if c1 > c1_max and status==1:
c1_max = c1
if c2 > c2_max and status==2:
c2_max = c2
else:
# end of subarry
if c1 > c1_max and status==1:
c1_max = c1
if c2 > c2_max and status==2:
c2_max = c2
c1 = 1
c2 = 1
status = (-1)
# if is odd
elif i%2!=0:
if arr[i]<arr[i+1]:
if status==2 or status==(-1):
c2+=1
status = 2
else:
c2+=1
c1 = 1
status = (2)
if c1 > c1_max and status==1:
c1_max = c1
if c2 > c2_max and status==2:
c2_max = c2
elif arr[i]>arr[i+1]:
if status==1 or status==(-1):
c1+=1
status = 1
else:
c1+=1
c2 = 1
status = (1)
if c1 > c1_max and status==1:
c1_max = c1
if c2 > c2_max and status==2:
c2_max = c2
else:
status = (-1)
if c1 > c1_max:
c1_max = c1
if c2 > c2_max:
c2_max = c2
c1 = 1
c2 = 1
if c1_max > c2_max:
print("c1")
return c1_max
elif c1_max == c2_max and c1_max==(-1):
print("the same")
return 1
else: #c2_max > c1_max or (c1_max == c2_max and c1_max!=(-1))
print("c2")
return c2_max
Medium
LeetCode 付費版在坑錢? Is LeetCode Premium Worth It in 2021?