My first approach was to traverse forward and backward to check the longest monotonic subarray but this approach will take a long time as I will have to traverse twice. Instead, I'll used two pointer.
I used two variables, inc_len
and dec_len
, to track the length of the current increasing and decreasing subarrays, respectively. As I traverse the array, I compare each element with the previous one. If the current element is greater, I increment inc_len
and reset dec_len
to 1. If it is smaller, I increment dec_len
and reset inc_len
to 1. If they are equal, I reset both counters to 1.
class Solution:
def longestMonotonicSubarray(self, nums: List[int]) -> int:
if not nums:
return None
inc_len, dec_len = 1, 1
max_len = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
inc_len += 1
dec_len = 1
elif nums[i] < nums[i - 1]:
dec_len += 1
inc_len = 1
else:
inc_len, dec_len = 1, 1
max_len = max(max_len, inc_len, dec_len)
return max_len
- Time: O(n)
- Space: O(1)
