Longest equal substring with cost less than K | Function to find the maximum length ; Fill the prefix array with the difference of letters ; Update the maximum length ; Driver code
function solve ( X , Y , N , K ) { let count = new Array ( N + 1 ) ; count . fill ( 0 ) ; let sol = 0 ; count [ 0 ] = 0 ; for ( let i = 1 ; i <= N ; i ++ ) { count [ i ] = count [ i - 1 ] + Math . abs ( X [ i - 1 ] . charCodeAt ( ) - Y [ i - 1 ] . charCodeAt ( ) ) ; } let j = 0 ; for ( let i = 1 ; i <= N ; i ++ ) { while ( ( count [ i ] - count [ j ] ) > K ) { j ++ ; } sol = Math . max ( sol , i - j ) ; } return sol ; } let N = 4 ; let X = " " , Y = " " ; let K = 3 ; document . write ( solve ( X , Y , N , K ) ) ;