Maximum length sub | Function to return the maximum length of the required sub - array ; To store the maximum length for a valid subarray ; To store the count of contiguous similar elements for previous group and the current group ; If current element is equal to the previous element then it is a part of the same group ; Else update the previous group and start counting elements for the new group ; Update the maximum possible length for a group ; Return the maximum length of the valid subarray ; Driver code
def maxLength ( a , n ) : NEW_LINE INDENT maxLen = 0 ; NEW_LINE prev_cnt = 0 ; curr_cnt = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] == a [ i - 1 ] ) : NEW_LINE INDENT curr_cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT prev_cnt = curr_cnt ; NEW_LINE curr_cnt = 1 ; NEW_LINE DEDENT maxLen = max ( maxLen , min ( prev_cnt , curr_cnt ) ) ; NEW_LINE DEDENT return ( 2 * maxLen ) ; NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 0 , 0 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxLength ( arr , n ) ) ; NEW_LINE