You are given an array arr
of integers. You need to find the length of the longest subarray that is either strictly increasing or strictly decreasing.
To solve this problem, we need to iterate through the array and keep track of the lengths of the currently observed strictly increasing or strictly decreasing subarrays. We can maintain a few state variables:
curr_inc_length
for the length of the current strictly increasing subarray.curr_dec_length
for the length of the current strictly decreasing subarray.max_length
to store the maximum length observed so far of either type of subarray.We will iterate through the array from the second element and for each element, we will:
curr_inc_length
, reset curr_dec_length
to 1.curr_dec_length
, reset curr_inc_length
to 1.curr_inc_length
and curr_dec_length
to 1.max_length
accordingly.def longest_strictly_inc_or_dec_subarray(arr):
if not arr:
return 0
if len(arr) == 1:
return 1
curr_inc_length = 1
curr_dec_length = 1
max_length = 1
for i in range(1, arr.length):
if arr[i] > arr[i - 1]:
curr_inc_length += 1
curr_dec_length = 1
elif arr[i] < arr[i - 1]:
curr_dec_length += 1
curr_inc_length = 1
else:
curr_inc_length = 1
curr_dec_length = 1
max_length = max(max_length, curr_inc_length, curr_dec_length)
return max_length
# Example usage:
# arr = [1, 2, 3, 4, 1, 0, -1, -2]
# print(longest_strictly_inc_or_dec_subarray(arr)) # Output: 4
This solution efficiently finds the length of the longest strictly increasing or strictly decreasing subarray using a single traversal of the input array and constant additional space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?