Minimize cost to convert all occurrences of each distinct character to lowercase or uppercase | C ++ program for the above approach ; Function to find the minimum cost to convert all distinct characters to either uppercase or lowercase ; Store the size of the string ; Stores the frequency of lowercase & uppercase characters respectively ; Traverse the string S ; Update uppercase frequency of s [ i ] ; Otherwise , update lowercase frequency of s [ i ] ; Stores if the i - th character should be lowercase or not ; Iterate over the range [ 0 , 25 ] ; If the character is present in the string ; Store the cost to convert every occurence of i to uppercase and lowercase ; Update result [ i ] to 1 if lowercase cost is less ; Traverse the string S ; Store the index of the character ; Convert the current character to uppercase or lowercase according to the condition ; Update s [ i ] ; Update s [ i ] ; Print the modified string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( string s , int L , int U ) { int N = s . size ( ) ; string ans = " " ; int lowerFreq [ 26 ] = { 0 } ; int upperFreq [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { if ( isupper ( s [ i ] ) ) upperFreq [ s [ i ] - ' A ' ] ++ ; else lowerFreq [ s [ i ] - ' a ' ] ++ ; } int result [ 26 ] = { 0 } ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( lowerFreq [ i ] != 0 upperFreq [ i ] != 0 ) { int costToUpper = U * lowerFreq [ i ] ; int costToLower = L * upperFreq [ i ] ; if ( costToLower < costToUpper ) { result [ i ] = 1 ; } } } for ( int i = 0 ; i < N ; i ++ ) { int index = 0 ; if ( islower ( s [ i ] ) ) index = s [ i ] - ' a ' ; else index = s [ i ] - ' A ' ; if ( result [ index ] == 1 ) { s [ i ] = tolower ( s [ i ] ) ; } else { s [ i ] = toupper ( s [ i ] ) ; } } cout << s ; } int main ( ) { string S = " aabbAA " ; int L = 1 , U = 1 ; minimumCost ( S , L , U ) ; return 0 ; }