Cost to make a string Panagram | Set 2 | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int costToPanagram ( string str , int cost [ ] ) { int i , n = str . length ( ) ; int occurrences [ 26 ] = { 0 } ; for ( i = 0 ; i < n ; i ++ ) occurrences [ str [ i ] - ' a ' ] ++ ; int 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 ) ; } int main ( ) { int 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 } ; string str = " geeksforgeeks " ; cout << costToPanagram ( str , cost ) ; }