Length of the 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
def lenOfLongZigZagArr ( a , n ) : NEW_LINE INDENT _max = 1 NEW_LINE _len = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if i % 2 == 0 and a [ i ] < a [ i + 1 ] : NEW_LINE INDENT _len += 1 NEW_LINE DEDENT elif i % 2 == 1 and a [ i ] > a [ i + 1 ] : NEW_LINE INDENT _len += 1 NEW_LINE DEDENT else : NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if _max < _len : NEW_LINE INDENT _max = _len NEW_LINE DEDENT _len = 1 NEW_LINE DEDENT ' NEW_LINE INDENT if _max < _len : NEW_LINE INDENT _max = _len NEW_LINE DEDENT return _max NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( lenOfLongZigZagArr ( arr , n ) ) NEW_LINE