-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
longest-strictly-increasing-or-strictly-decreasing-subarray.py
66 lines (60 loc) · 1.59 KB
/
longest-strictly-increasing-or-strictly-decreasing-subarray.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Time: O(n)
# Space: O(1)
# array
class Solution(object):
def longestMonotonicSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = cnt = 1
curr = prev = 0
for i in xrange(1, len(nums)):
curr = cmp(nums[i-1], nums[i])
if curr == 0:
cnt = 1
continue
else:
cnt = (cnt if curr == prev else 1)+1
result = max(result, cnt)
prev = curr
return result
# Time: O(n)
# Space: O(1)
# array
class Solution2(object):
def longestMonotonicSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = cnt1 = cnt2 = 1
for i in xrange(1, len(nums)):
if nums[i-1] < nums[i]:
cnt1 += 1
cnt2 = 1
elif nums[i-1] > nums[i]:
cnt2 += 1
cnt1 = 1
else:
cnt1 = cnt2 = 1
result = max(result, cnt1, cnt2)
return result
# Time: O(n)
# Space: O(1)
# array
class Solution3(object):
def longestMonotonicSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def f(compare):
result = l = 0
for i in xrange(len(nums)):
l += 1
if i+1 == len(nums) or not compare(nums[i], nums[i+1]):
result = max(result, l)
l = 0
return result
return max(f(lambda x, y: x < y), f(lambda x, y: x > y))