import
java.io.*;
import
java.util.*;
class
GFG {
public
static
int
maxScoreWords(
String[] words,
char
[] letters,
int
[] score)
{
int
[] letterCounts =
new
int
[
26
];
for
(
char
letter : letters)
letterCounts[letter -
'a'
]++;
return
helper(words,
0
, letterCounts,
score,
new
HashMap<>());
}
public
static
int
helper(
String[] words,
int
start,
int
[] letterCounts,
int
[] score,
Map<String, Integer> memo)
{
if
(start == words.length)
return
0
;
String key = getKey(letterCounts, start);
if
(memo.containsKey(key))
return
memo.get(key);
int
currScore =
0
;
int
wordScore =
0
;
int
[] nextCounts = letterCounts.clone();
for
(
int
i =
0
;
i < words[start].length();
++i) {
int
idx = words[start].charAt(i) -
'a'
;
if
(nextCounts[idx] ==
0
) {
wordScore = -
1
;
break
;
}
wordScore += score[idx];
nextCounts[idx]--;
}
if
(wordScore >
0
)
currScore = helper(words, start +
1
,
nextCounts,
score, memo)
+ wordScore;
currScore = Math.max(
currScore, helper(words, start +
1
,
letterCounts, score,
memo));
memo.put(key, currScore);
return
currScore;
}
public
static
String getKey(
int
[] letterCounts,
int
idx)
{
StringBuilder sb =
new
StringBuilder();
for
(
int
i =
0
; i <
26
; ++i)
sb.append(letterCounts[i]);
sb.append(
', '
);
sb.append(idx);
return
sb.toString();
}
public
static
void
main(String[] args)
{
String words[] = {
"dog"
,
"cat"
,
"dad"
,
"good"
};
char
letters[] = {
'a'
,
'a'
,
'c'
,
'd'
,
'd'
,
'd'
,
'g'
,
'o'
,
'o'
};
int
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
};
System.out.println(
maxScoreWords(words, letters,
score));
}
}