Maximum Score Words Formed by Letters — LeetCode 1255 Python Solution

HardBit ManipulationArrayHash TableStringDynamic ProgrammingBacktrackingBitmaskCounting
Problem
#1255
Reading time
3 min

The problem

Given a list of words, list of single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).

Example

Input
words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], 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]
Output
23
Explanation
Score a=1, c=9, d=5, g=3, o=2

Python solution

Python
class Solution:
    def maxScoreWords(
        self, words: List[str], letters: List[str], score: List[int]
    ) -> int:
        cnt = Counter(letters)
        n = len(words)
        ans = 0
        for i in range(1 << n):
            cur = Counter(''.join([words[j] for j in range(n) if i >> j & 1]))
            if all(v <= cnt[c] for c, v in cur.items()):
                t = sum(v * score[ord(c) - ord('a')] for c, v in cur.items())
                ans = max(ans, t)
        return ans

Complexity

MeasureComplexity
Time(2^n \times n \times M)
SpaceO(C) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1255. Maximum Score Words Formed by Letters is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1255. Maximum Score Words Formed by Letters?
LeetCode 1255. Maximum Score Words Formed by Letters is rated Hard on LeetCode.
What is the time complexity of LeetCode 1255. Maximum Score Words Formed by Letters?
The Python solution on this page runs in (2^n \times n \times M).
What is the space complexity of LeetCode 1255. Maximum Score Words Formed by Letters?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 1255. Maximum Score Words Formed by Letters cover?
LeetCode 1255. Maximum Score Words Formed by Letters is tagged Bit Manipulation, Array, Hash Table, String, Dynamic Programming, Backtracking, Bitmask and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview