Given an integer array nums
and an integer threshold
, the task is to find the length of the longest subarray that meets the following criteria:
threshold
.nums
is a list of integers.threshold
is a single integer.def longest_even_odd_subarray(nums, threshold):
max_length = 0
current_length = 0
n = len(nums)
if n == 0:
return 0
for i in range(n):
if nums[i] > threshold:
current_length = 0
continue
if i == 0 or (nums[i] <= threshold and nums[i-1] <= threshold and
((nums[i] % 2 == 0 and nums[i-1] % 2 != 0) or (nums[i] % 2 != 0 and nums[i-1] % 2 == 0))):
current_length += 1
else:
current_length = 1
max_length = max(max_length, current_length)
return max_length
# Example usage:
nums = [3, 2, 5, 4, 5, 6, 7, 8]
threshold = 5
print(longest_even_odd_subarray(nums, threshold)) # Output: 4
The time complexity of this approach is O(n)
where n
is the number of elements in the array. This is because we are making a single pass through the array to determine the longest valid subarray length.
The space complexity is O(1)
because we only use a few extra variables for tracking lengths and pointers, independent of the input size.
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?