Longest substring of only 4 's from the first N characters of the infinite string | PHP 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 result ; Initialize prefix sum array of characters and product variable ; Preprocessing of prefix sum array ; Initialize variable to store the string length where N belongs to ; Finding the string length where N belongs to ; Driver Code
< ? php $ MAXN = 30 ; function countMaxLength ( $ N ) { $ res = 0 ; $ pre = array ( ) ; $ p = 1 ; $ pre [ 0 ] = 0 ; for ( $ i = 1 ; $ i < $ GLOBALS [ ' AXN ' ; $ i ++ ) { $ p *= 2 ; $ pre [ $ i ] = $ pre [ $ i - 1 ] + $ i * $ p ; } $ ind = 0 ; for ( $ i = 1 ; $ i < $ GLOBALS [ ' AXN ' ; $ i ++ ) { if ( $ pre [ $ i ] >= $ N ) { $ ind = $ i ; break ; } } $ x = $ N - $ pre [ $ ind - 1 ] ; $ y = 2 * $ ind - 1 ; if ( $ x >= $ y ) $ res = min ( $ x , $ y ) ; else $ res = max ( $ x , 2 * ( $ ind - 2 ) + 1 ) ; return $ res ; } $ N = 25 ; echo countMaxLength ( $ N ) ; ? >