Cost to make a string Panagram | Set 2 | Function to return the cost to make str a Panagram ; Count the occurrences of each lowercase character ; To store the total gain ; If some character is missing , it has to be added at twice the cost ; If some character appears more than once , all of its occurrences except 1 can be traded for some gain ; If gain is more than the cost ; Return the total cost if gain < 0 ; Driver code
function costToPanagram ( str , cost ) { var i , n = str . length ; var occurrences = Array ( 26 ) . fill ( 0 ) ; for ( i = 0 ; i < n ; i ++ ) occurrences [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; var gain = 0 ; for ( i = 0 ; i < 26 ; i ++ ) { if ( occurrences [ i ] == 0 ) gain -= ( 2 * cost [ i ] ) ; else if ( occurrences [ i ] > 1 ) gain += ( cost [ i ] * ( occurrences [ i ] - 1 ) ) ; } if ( gain >= 0 ) return 0 ; return ( gain * - 1 ) ; } var cost = [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] ; var str = " " ; document . write ( costToPanagram ( str , cost ) ) ;