-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution1255.cs
78 lines (66 loc) · 2.01 KB
/
Solution1255.cs
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution1255
{
/// <summary>
/// 1255. Maximum Score Words Formed by Letters - Hard
/// <a href="https://leetcode.com/problems/maximum-score-words-formed-by-letters">See the problem</a>
/// </summary>
public int MaxScoreWords(string[] words, char[] letters, int[] score)
{
var letterCount = new int[26];
foreach (var letter in letters)
{
letterCount[letter - 'a']++;
}
return MaxScoreWordsHelper(words, letterCount, score, 0, 0);
}
private int MaxScoreWordsHelper(string[] words, int[] letterCount, int[] score, int index, int currentScore)
{
if (index == words.Length)
{
return currentScore;
}
// Skip the current word
int maxScore = MaxScoreWordsHelper(words, letterCount, score, index + 1, currentScore);
// Try to include the current word
var word = words[index];
var wordCount = new int[26];
foreach (var c in word)
{
wordCount[c - 'a']++;
}
bool canInclude = true;
for (int i = 0; i < 26; i++)
{
if (wordCount[i] > letterCount[i])
{
canInclude = false;
break;
}
}
if (canInclude)
{
for (int i = 0; i < 26; i++)
{
letterCount[i] -= wordCount[i];
}
maxScore = Math.Max(maxScore, MaxScoreWordsHelper(words, letterCount, score, index + 1, currentScore + CalculateWordScore(word, score)));
for (int i = 0; i < 26; i++)
{
letterCount[i] += wordCount[i];
}
}
return maxScore;
}
private int CalculateWordScore(string word, int[] score)
{
int totalScore = 0;
foreach (var c in word)
{
totalScore += score[c - 'a'];
}
return totalScore;
}
}