-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC0357.py
35 lines (33 loc) · 1.38 KB
/
LC0357.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
W = len(words)
# Count how many times each letter occurs
freq = [0 for i in range(26)]
for c in letters:
freq[ord(c) - 97] += 1
# Calculate score of subset
def subset_score(subset_letters, score, freq):
total_score = 0
for c in range(26):
total_score += subset_letters[c] * score[c]
# Check if we have enough of each letter to build this subset of words
if subset_letters[c] > freq[c]:
return 0
return total_score
max_score = 0
# Iterate over every subset of words
subset_letters = {}
for mask in range(1 << W):
# Reset the subset_letters map
subset_letters = [0 for i in range(26)]
# Find words in this subset
for i in range(W):
if (mask & (1 << i)) > 0:
# Count the letters in this word
L = len(words[i])
for j in range(L):
subset_letters[ord(words[i][j]) - 97] += 1
# Calculate score of subset
max_score = max(max_score, subset_score(subset_letters, score, freq))
# Return max_score as the result
return max_score