#1255

Maximum Score Words Formed by Letters

Hard
ArrayHash TableStringDynamic ProgrammingBacktrackingBit ManipulationCountingBitmaskHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^n * m)
O(n * m)
Space
O(n)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

We can use a backtracking approach with pruning to explore valid combinations of words while keeping track of the letter counts. This avoids unnecessary calculations and improves efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency map of the available letters.
  2. 2Step 2: Use a recursive function to explore each word and decide whether to include it or not.
  3. 3Step 3: If including a word exceeds the available letters, skip that branch.
  4. 4Step 4: Keep track of the maximum score during the recursion.
solution.py24 lines
1# Full working Python code
2from collections import Counter
3
4def maxScoreWords(words, letters, score):
5    letter_count = Counter(letters)
6    max_score = [0]
7
8    def backtrack(index, current_score):
9        if index == len(words):
10            max_score[0] = max(max_score[0], current_score)
11            return
12        # Skip the current word
13        backtrack(index + 1, current_score)
14        # Include the current word
15        word_count = Counter(words[index])
16        if all(word_count[ch] <= letter_count[ch] for ch in word_count):
17            for ch in word_count:
18                letter_count[ch] -= word_count[ch]
19            backtrack(index + 1, current_score + sum(score[ord(ch) - ord('a')] * word_count[ch] for ch in word_count))
20            for ch in word_count:
21                letter_count[ch] += word_count[ch]
22
23    backtrack(0, 0)
24    return max_score[0]

Complexity note: The time complexity is O(n * m) where n is the number of words and m is the average length of words. The space complexity is O(n) for storing letter counts.

  • 1Use backtracking to explore combinations efficiently.
  • 2Prune branches that exceed letter limits early.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.