Minimize cost to convert all occurrences of each distinct character to lowercase or uppercase | 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
function minimumCost ( str , L , U ) { var N = str . length ; var s = str . split ( " " ) ; string ans = " " ; var lowerFreq = new Array ( 26 ) . fill ( 0 ) ; var upperFreq = new Array ( 26 ) . fill ( 0 ) ; for ( var i = 0 ; i < N ; i ++ ) { if ( s [ i ] === s [ i ] . toUpperCase ( ) ) upperFreq [ s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; else lowerFreq [ s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; } var result = new Array ( 26 ) . fill ( 0 ) ; for ( var i = 0 ; i < 26 ; i ++ ) { if ( lowerFreq [ i ] !== 0 upperFreq [ i ] !== 0 ) { var costToUpper = U * lowerFreq [ i ] ; var costToLower = L * upperFreq [ i ] ; if ( costToLower < costToUpper ) { result [ i ] = 1 ; } } } for ( var i = 0 ; i < N ; i ++ ) { var index = 0 ; if ( s [ i ] === s [ i ] . toLowerCase ( ) ) index = s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ; else index = s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ; if ( result [ index ] === 1 ) { s [ i ] = s [ i ] . toLowerCase ( ) ; } else { s [ i ] = s [ i ] . toUpperCase ( ) ; } } document . write ( s . join ( " " ) ) ; } var S = " " ; var L = 1 , U = 1 ; minimumCost ( S , L , U ) ;