|
| 1 | +class Solution { |
| 2 | + |
| 3 | + Map<Character, Integer> freq; |
| 4 | + int[] scoree; |
| 5 | + |
| 6 | + public int maxScoreWords(String[] words, char[] letters, int[] score) { |
| 7 | + scoree = score; |
| 8 | + freq = new HashMap<>(); |
| 9 | + for(char c: letters){ |
| 10 | + freq.put(c, freq.getOrDefault(c, 0) + 1); |
| 11 | + } |
| 12 | + |
| 13 | + return backtrack(words, 0); |
| 14 | + } |
| 15 | + private int backtrack(String[] words, int idx){ |
| 16 | + if(idx == words.length) |
| 17 | + return 0; |
| 18 | + |
| 19 | + int res = backtrack(words, idx + 1); |
| 20 | + if(can_form_word(words[idx])){ |
| 21 | + for(char c: words[idx].toCharArray()) |
| 22 | + freq.put(c, freq.get(c) - 1); |
| 23 | + |
| 24 | + res = Math.max(res, get_score(words[idx]) + backtrack(words, idx + 1)); |
| 25 | + for(char c: words[idx].toCharArray()) |
| 26 | + freq.put(c, freq.get(c) + 1); |
| 27 | + } |
| 28 | + return res; |
| 29 | + } |
| 30 | + private boolean can_form_word(String s){ |
| 31 | + Map<Character, Integer> map = new HashMap<>(); |
| 32 | + for(char c: s.toCharArray()) |
| 33 | + map.put(c, map.getOrDefault(c, 0) + 1); |
| 34 | + |
| 35 | + for(char c: map.keySet()){ |
| 36 | + if(!freq.containsKey(c) || map.get(c) > freq.get(c)) |
| 37 | + return false; |
| 38 | + } |
| 39 | + return true; |
| 40 | + } |
| 41 | + private int get_score(String s){ |
| 42 | + int score = 0; |
| 43 | + for(char c: s.toCharArray()){ |
| 44 | + score += scoree[c - 'a']; |
| 45 | + } |
| 46 | + return score; |
| 47 | + } |
| 48 | +} |
0 commit comments