Length of the longest ZigZag subarray of the given array | Java implementation to find the length of longest zigzag subarray of the given array ; Function to find the length of longest zigZag contiguous subarray ; ' max ' to store the length of longest zigZag subarray ; ' len ' to store the lengths of longest zigZag subarray at different instants of time ; Traverse the array from the beginning ; Check if ' max ' length is less than the length of the current zigzag subarray . If true , then update ' max ' ; Reset ' len ' to 1 as from this element , again the length of the new zigzag subarray is being calculated ; comparing the length of the last zigzag subarray with ' max ' ; Return required maximum length ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int lenOfLongZigZagArr ( int a [ ] , int n ) { int max = 1 , len = 1 ; 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 { if ( max < len ) max = len ; len = 1 ; } } if ( max < len ) max = len ; return max ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; System . out . println ( lenOfLongZigZagArr ( arr , n ) ) ; } }