Maximize cost of forming a set of words using given set of characters | Function to find the maximum cost of any valid set of words formed by using the given letters ; Stores frequency of characters ; Find the maximum cost ; Utility function to find maximum cost of generating any possible subsets of strings ; Base Case ; Stores the current cost ; Stores the cost of by the current word ; Create a copy of the letterCounts array ; Traverse the current word ; Store the current index & check if its frequency is 0 or not ; If true , then update wordScore to - 1 ; Otherwise , add the cost of the current index to wordScore ; Decrease its frequency ; If wordScore > 0 , then recursively call for next index ; Find the cost by not including current word ; Return the maximum score ; Given arrays ; Function Call
function maxScoreWords ( words , letters , score ) { let letterCounts = new Array ( 26 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { letterCounts [ i ] = 0 ; } for ( let letter = 0 ; letter < letters . length ; letter ++ ) letterCounts [ letters [ letter ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; return helper ( words , 0 , letterCounts , score ) ; } function helper ( words , start , letterCounts , score ) { if ( start == words . length ) return 0 ; let currScore = 0 ; let wordScore = 0 ; let nextCounts = [ ... letterCounts ] ; for ( let i = 0 ; i < words [ start ] . length ; ++ i ) { let idx = words [ start ] [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; if ( nextCounts [ idx ] == 0 ) { wordScore = - 1 ; break ; } wordScore += score [ idx ] ; nextCounts [ idx ] -- ; } if ( wordScore > 0 ) currScore = helper ( words , start + 1 , nextCounts , score ) + wordScore ; currScore = Math . max ( currScore , helper ( words , start + 1 , letterCounts , score ) ) ; return currScore ; } let words = [ " " , " " , " " , " " ] ; let letters = [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] ; let score = [ 1 , 0 , 9 , 5 , 0 , 0 , 3 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ; document . write ( maxScoreWords ( words , letters , score ) ) ;