Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | Java program for the above approach ; 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 ; Driver Code ; Given String ; Given queries ; Function Call
import java . util . * ; class GFG { static void maxDiffFreq ( int [ ] [ ] queries , String S ) { int N = S . length ( ) ; int Q = queries . length ; for ( int i = 0 ; i < Q ; ++ i ) { int l = queries [ i ] [ 0 ] - 1 ; int r = queries [ i ] [ 1 ] - 1 ; int freq [ ] = new int [ 26 ] ; for ( int j = l ; j <= r ; j ++ ) { freq [ S . charAt ( j ) - ' a ' ] ++ ; } int mx = 0 ; int mn = 99999999 ; for ( int j = 0 ; j < 26 ; j ++ ) { mx = Math . max ( mx , freq [ j ] ) ; if ( freq [ j ] > 0 ) mn = Math . min ( mn , freq [ j ] ) ; } System . out . print ( mx - mn + "NEW_LINE"); } } public static void main ( String [ ] args ) { String S = " abaabac " ; int [ ] [ ] queries = { { 2 , 6 } , { 1 , 7 } } ; maxDiffFreq ( queries , S ) ; } }