Fill the prefix array with the difference of letters
for ( int i = 1 ; i <= N ; i ++ ) { count [ i ] = count [ i - 1 ] + abs ( X [ i - 1 ] - Y [ i - 1 ] ) ; } int j = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { while ( ( count [ i ] - count [ j ] ) > K ) { j ++ ; }