Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | Function to find difference between maximum and minimum frequency of a character in given range ; Stores length of string ; Stores count of queries ; Iterate over the characters of the string ; Stores l - value of a query ; Stores r - value of a query ; Store count of every character laying in range [ l , r ] ; Update frequency of current character ; Stores maximum frequency of characters in given range ; Stores minimum frequency of characters in given range ; Iterate over all possible characters of the given string ; Update mx ; If ( j + ' a ' ) is present ; Difference between max and min ; Given string ; Given queries ; Function Call
function maxDiffFreq ( queries , S ) { let N = S . length ; let Q = queries . length ; for ( let i = 0 ; i < Q ; ++ i ) { let l = queries [ i ] [ 0 ] - 1 ; let r = queries [ i ] [ 1 ] - 1 ; let freq = new Array ( 26 ) . fill ( 0 ) ; for ( let j = l ; j <= r ; j ++ ) { freq [ S [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } let mx = 0 ; let mn = 99999999 ; for ( let j = 0 ; j < 26 ; j ++ ) { mx = Math . max ( mx , freq [ j ] ) ; if ( freq [ j ] ) mn = Math . min ( mn , freq [ j ] ) ; } document . write ( mx - mn + " " ) ; } } let S = " " ; let queries = [ [ 2 , 6 ] , [ 1 , 7 ] ] ; maxDiffFreq ( queries , S ) ;