![]() |
VOOZH | about |
Given an array a[] of N integers, the task is to find the length of the longest Alternating Even Odd subarray present in the array.
Examples:
Input: a[] = {1, 2, 3, 4, 5, 7, 9}
Output: 5
Explanation:
The subarray {1, 2, 3, 4, 5} has alternating even and odd elements.Input: a[] = {1, 3, 5}
Output: 0
Explanation:
There is no such alternating sequence possible.
The idea is to consider every subarray and find the length of even and odd subarrays.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
5
Time Complexity: O(N2), Iterating over every subarray therefore N2 are possible
Auxiliary Space: O(1)
Observe that the Sum of two even numbers is even, the Sum of two odd numbers is even but the sum of one even and one odd number is odd.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
5
Time Complexity: O(N), Traversing over the array one time.
Auxiliary Space: O(1)
By simply storing the nature of the previous element we encounter( odd or even) and comparing it with the next element.
Follow the steps below to solve the problem:
Below is the implementation of above approach:
Length of longest subarray of even and odds is : 5
Time Complexity: O(N), Since we need to iterate over the whole array once
Auxiliary Space: O(1)