Minimize cost to convert all occurrences of each distinct character to lowercase or uppercase | Java 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void minimumCost ( String str , int L , int U ) { int N = str . length ( ) ; char s [ ] = str . toCharArray ( ) ; String ans = " " ; int lowerFreq [ ] = new int [ 26 ] ; int upperFreq [ ] = new int [ 26 ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( Character . isUpperCase ( s [ i ] ) ) upperFreq [ s [ i ] - ' A ' ] ++ ; else lowerFreq [ s [ i ] - ' a ' ] ++ ; } int result [ ] = new int [ 26 ] ; 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 ( Character . isLowerCase ( s [ i ] ) ) index = s [ i ] - ' a ' ; else index = s [ i ] - ' A ' ; if ( result [ index ] == 1 ) { s [ i ] = Character . toLowerCase ( s [ i ] ) ; } else { s [ i ] = Character . toUpperCase ( s [ i ] ) ; } } System . out . println ( new String ( s ) ) ; } public static void main ( String [ ] args ) { String S = " aabbAA " ; int L = 1 , U = 1 ; minimumCost ( S , L , U ) ; } }