Longest substring of only 4 's from the first N characters of the infinite string | Python 3 implementation of the approach ; Function to return the length of longest contiguous string containing only 4 aTMs from the first N characters of the string ; Initialize prefix sum array of characters and product variable ; Preprocessing of prefix sum array ; Finding the string length where N belongs to ; Driver Code
MAXN = 30 NEW_LINE def countMaxLength ( N ) : NEW_LINE INDENT pre = [ 0 for i in range ( MAXN ) ] NEW_LINE p = 1 NEW_LINE pre [ 0 ] = 0 NEW_LINE for i in range ( 1 , MAXN , 1 ) : NEW_LINE INDENT p *= 2 NEW_LINE pre [ i ] = pre [ i - 1 ] + i * p NEW_LINE DEDENT for i in range ( 1 , MAXN , 1 ) : NEW_LINE INDENT if ( pre [ i ] >= N ) : NEW_LINE INDENT ind = i NEW_LINE break NEW_LINE DEDENT DEDENT x = N - pre [ ind - 1 ] NEW_LINE y = 2 * ind - 1 NEW_LINE if ( x >= y ) : NEW_LINE INDENT res = min ( x , y ) NEW_LINE DEDENT else : NEW_LINE INDENT res = max ( x , 2 * ( ind - 2 ) + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE print ( countMaxLength ( N ) ) NEW_LINE DEDENT