-
Notifications
You must be signed in to change notification settings - Fork 0
/
1255. Maximum score words formed by letters
48 lines (35 loc) · 1.17 KB
/
1255. Maximum score words formed by letters
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
36
37
38
39
40
41
42
43
44
45
46
47
48
//1255. Maximum score words formed by letters
class Solution {
public int maxScoreWords(String[] words, char[] letters, int[] score) {
int [] frequency = new int[26];
for(int i = 0; i < letters.length; i++) {
frequency[letters[i] - 'a']++;
}
int result = backtrack(words, frequency, score, 0);
return result;
}
public static int backtrack(String[] words, int[] frr, int[] score,int idx){
if(idx == words.length) {
return 0;
}
int scoreOfaWord = 0;
int no = backtrack(words, frr, score, idx + 1);
boolean isValid = true;
for(int i = 0; i < words[idx].length(); i++) {
char ch = words[idx].charAt(i);
if(frr[ch - 'a'] <= 0) {
isValid = false;
}
frr[ch - 'a']--;
scoreOfaWord += score[ch - 'a'];
}
int yes = 0;
if(isValid) {
yes = scoreOfaWord + backtrack(words, frr, score, idx + 1);
}
for(int i = 0; i < words[idx].length(); i++) {
frr[words[idx].charAt(i) - 'a']++;
}
return Math.max(no, yes);
}
}