Given an array containing n numbers. The problem is to find the length of the longest zigZag subarray such that every element in the subarray should be in form a < b > c < d > e < f.. Time Complexity should be O(n).
Examples:
Input : arr[] = {1, 5, 0, 4, 3}
Output : 5
The subarray is {1, 5, 0, 4, 3}
Input : arr[] = {12, 13, 1, 5, 4, 7, 8, 10, 10, 11}
Output : 4
The subarray is {12, 13, 1, 5, 4, 7}
Input : arr[] = {1, 2, 3, 4, 5}
Output : 2
The subarray is {1, 2} or {2, 3} or {4, 5}
Approach:
- Initially initialize cnt as 1.
- Iterate among the array elements, check if elements are in form a < b > c < d > e < f.. .
- If true Increase the cnt by 1.
- If it is not in form a < b > c < d > e < f.. , then re-initialize cnt by 1.
// C++ implementation to find the length of
// the longest zigzag subarray
#include <bits/stdc++.h>
using namespace std;
// Function to find the length of the longest zigzag contiguous subarray
int lenOfLongZigZagArr(int a[], int n)
{
// 'maxLen' to store the length of the longest zigzag subarray
// 'len' to store the current length of the zigzag subarray
int maxLen = 1, len = 1;
// Traverse the array from the first element
for (int i = 0; i < n - 1; i++)
{
if (i % 2 == 0 && (a[i] < a[i + 1]))
len++;
else if (i % 2 == 1 && (a[i] > a[i + 1]))
len++;
else
{
// Check if 'maxLen' is less than the length of the current zigzag subarray
// If true, update 'maxLen'
if (maxLen < len)
maxLen = len;
// Reset 'len' to 1 as a new zigzag subarray starts
len = 1;
}
}
// Compare the length of the last zigzag subarray with 'maxLen'
if (maxLen < len)
maxLen = len;
// Return the maximum length
return maxLen;
}
// Driver program to test the above function
int main()
{
int arr[] = {1, 5, 0, 4, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length = " << lenOfLongZigZagArr(arr, n);
return 0;
}
Output:
5
