|
| 1 | +/** |
| 2 | + * 1255. Maximum Score Words Formed by Letters |
| 3 | + * https://leetcode.com/problems/maximum-score-words-formed-by-letters/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a list of words, list of single letters (might be repeating) and score of every character. |
| 7 | + * |
| 8 | + * Return the maximum score of any valid set of words formed by using the given letters (words[i] |
| 9 | + * cannot be used two or more times). |
| 10 | + * |
| 11 | + * It is not necessary to use all characters in letters and each letter can only be used once. |
| 12 | + * Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] |
| 13 | + * respectively. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {string[]} words |
| 18 | + * @param {character[]} letters |
| 19 | + * @param {number[]} score |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var maxScoreWords = function(words, letters, score) { |
| 23 | + const letterCount = new Array(26).fill(0); |
| 24 | + for (const letter of letters) { |
| 25 | + letterCount[letter.charCodeAt(0) - 97]++; |
| 26 | + } |
| 27 | + return calculateMaxScore(0, letterCount); |
| 28 | + |
| 29 | + function calculateMaxScore(index, available) { |
| 30 | + if (index === words.length) return 0; |
| 31 | + |
| 32 | + const skipScore = calculateMaxScore(index + 1, available); |
| 33 | + const word = words[index]; |
| 34 | + const tempCount = [...available]; |
| 35 | + let canUse = true; |
| 36 | + let wordScore = 0; |
| 37 | + |
| 38 | + for (const char of word) { |
| 39 | + const charIndex = char.charCodeAt(0) - 97; |
| 40 | + if (tempCount[charIndex] === 0) { |
| 41 | + canUse = false; |
| 42 | + break; |
| 43 | + } |
| 44 | + tempCount[charIndex]--; |
| 45 | + wordScore += score[charIndex]; |
| 46 | + } |
| 47 | + |
| 48 | + const useScore = canUse ? wordScore + calculateMaxScore(index + 1, tempCount) : 0; |
| 49 | + return Math.max(skipScore, useScore); |
| 50 | + } |
| 51 | +}; |
0 commit comments