← Home

1255. Maximum Score Words Formed by Letters

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
125

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1255. Maximum Score Words Formed by Letters, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are maxScoreWords, updateScore, generateSubset.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 292 ms, faster than 7.68% of C++ online submissions for Maximum Score Words Formed by Letters.
02//Memory Usage: 53.4 MB, less than 100.00% of C++ online submissions for Maximum Score Words Formed by Letters.
03
04class Solution {
05public:
06    int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) {
07        int wordScore, combScore, maxScore = 0;
08        vector<int> wordsScore;
09        map<char, int> lettersCount, wordCount, combCount;
10        bool combExist;
11        
12        //create the map lettersCount
13        for(char c : letters){
14            if(lettersCount.find(c) == lettersCount.end()){
15                lettersCount[c] = 1;
16            }else{
17                lettersCount[c]++;
18            }
19        }
20        
21        //calculate scores of words, fill wordsScore
22        for(string word : words){
23            wordCount.clear();
24            wordScore = 0;
25            for(char c : word){
26                if(wordCount.find(c) == wordCount.end()){
27                    wordCount[c] = 1;
28                }else{
29                    wordCount[c]++;
30                }
31                
32                if(wordCount[c] <= lettersCount[c]){
33                    wordScore += score[c-'a'];
34                }else{
35                    //this word cannot be formed
36                    wordScore = 0;
37                    break;
38                }
39            }
40            wordsScore.push_back(wordScore);
41            // cout << wordScore << " ";
42        }
43        // cout << endl;
44        
45        //enumerate 2^words.length possibles
46        for(int num = 0; num < pow(2, words.size()); num++){
47            combScore = 0;
48            combCount.clear();
49            combExist = true;
50            for(int i = 0; i < words.size(); i++){
51                //(num/(pow(2,i)))%2: imagine "num" as a binary number
52                //then num/(pow(2,i)) is the part that after "num"'s i'th bit
53                //(num/(pow(2,i)))%2 is the i'th bit of "num"
54                if( (int)(num/(pow(2,i))) %2 == 1){
55                    //check if this combination exist
56                    for(char c : words[i]){
57                        if(combCount.find(c) == combCount.end()){
58                            combCount[c] = 1;
59                        }else{
60                            combCount[c]++;
61                        }
62                        
63                        if(combCount[c] > lettersCount[c]){
64                            combExist = false;
65                        }
66                    }
67                    
68                    if(!combExist){
69                        combScore = 0;
70                        break;
71                    }else{
72                        combScore += wordsScore[i];
73                    }
74                }
75            }
76            
77            if(combScore > maxScore){
78                // for(int i = 0; i < words.size(); i++){
79                //     cout << (int)(num/(pow(2,i))) %2;
80                // }
81                // cout << endl;
82                
83                maxScore = combScore;
84            }
85        }
86        
87        return maxScore;
88    }
89};
90
91//Runtime: 48 ms, faster than 20.85% of C++ online submissions for Maximum Score Words Formed by Letters.
92//Memory Usage: 36.2 MB, less than 100.00% of C++ online submissions for Maximum Score Words Formed by Letters.
93//https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/425104/Detailed-Explanation-using-Recursion
94class Solution {
95public:
96    int maxScore = INT_MIN;
97    vector<bool> taken;
98    vector<int> count;
99    //same as the argument of maxScoreWords
100    vector<string> words;
101    vector<int> score;
102    
103    void updateScore(){
104        int curScore = 0;
105        vector<int> curCount = vector<int>(26, 0);
106        for(int i = 0; i < words.size(); i++){
107            if(taken[i]){
108                for(char c : words[i]){
109                    // cout << "curCount: " << curCount[c-'a'] << endl;
110                    // cout << "count: " << count[c-'a'] << endl;
111                    // cout << "curScore: " << curScore << endl;
112                    curCount[c-'a']++;
113                    if(curCount[c-'a'] > count[c-'a']){
114                        return;
115                    }
116                    curScore += score[c-'a'];
117                }
118            }
119        }
120        maxScore = max(maxScore, curScore);
121    };
122    
123    void generateSubset(int n){
124        //every time a subset("taken") is generated, 
125        //call updateScore to calculate the score of current combination,
126        //and update maxScore
127        if(n == 0){
128            updateScore();
129            return;
130        }
131        
132        taken[n-1] = true;
133        generateSubset(n-1);
134        
135        taken[n-1] = false;
136        generateSubset(n-1);
137    };
138    
139    int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) {
140        taken = vector<bool>(words.size(), false);
141        count = vector<int>(26, 0);
142        for(char c : letters){
143            count[c-'a']++;
144        }
145        this->words = words;
146        this->score = score;
147        
148        generateSubset(words.size());
149        return maxScore;
150    }
151};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.