Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxDiffFreq ( vector < pair < int , int > > queries , string S ) { int N = S . size ( ) ; int Q = queries . size ( ) ; for ( int i = 0 ; i < Q ; ++ i ) { int l = queries [ i ] . first - 1 ; int r = queries [ i ] . second - 1 ; int freq [ 26 ] = { 0 } ; for ( int j = l ; j <= r ; j ++ ) { freq [ S [ j ] - ' a ' ] ++ ; } int mx = 0 ; int mn = 99999999 ; for ( int j = 0 ; j < 26 ; j ++ ) { mx = max ( mx , freq [ j ] ) ; if ( freq [ j ] ) mn = min ( mn , freq [ j ] ) ; } cout << mx - mn << endl ; } } int main ( ) { string S = " abaabac " ; vector < pair < int , int > > queries { { 2 , 6 } , { 1 , 7 } } ; maxDiffFreq ( queries , S ) ; }