Skip to content

3035. Maximum Palindromes After Operations 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 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
class Solution {
 public:
  int maxPalindromesAfterOperations(vector<string>& words) {
    int ans = 0;
    int pairs = getPairs(words);

    for (const int length : getSortedLengths(words)) {
      const int needPairs = length / 2;
      if (pairs < needPairs)
        return ans;
      ++ans;
      pairs -= needPairs;
    }

    return ans;
  }

 private:
  int getPairs(const vector<string>& words) {
    int pairs = 0;
    unordered_map<char, int> count;

    for (const string& word : words)
      for (const char c : word)
        ++count[c];

    for (const auto& [_, freq] : count)
      pairs += freq / 2;

    return pairs;
  }

  vector<int> getSortedLengths(const vector<string>& words) {
    vector<int> lengths;
    for (const string& word : words)
      lengths.push_back(word.length());
    ranges::sort(lengths);
    return lengths;
  }
};
 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
class Solution {
  public int maxPalindromesAfterOperations(String[] words) {
    int ans = 0;
    int pairs = getPairs(words);

    for (final int length : getSortedLengths(words)) {
      final int neededPairs = length / 2;
      if (pairs < neededPairs)
        return ans;
      ++ans;
      pairs -= neededPairs;
    }

    return ans;
  }

  private int getPairs(String[] words) {
    int pairs = 0;
    Map<Character, Integer> count = new HashMap<>();

    for (final String word : words)
      for (final char c : word.toCharArray())
        count.merge(c, 1, Integer::sum);

    for (final int freq : count.values())
      pairs += freq / 2;

    return pairs;
  }

  private int[] getSortedLengths(String[] words) {
    int[] lengths = new int[words.length];
    for (int i = 0; i < words.length; ++i)
      lengths[i] = words[i].length();
    Arrays.sort(lengths);
    return lengths;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maxPalindromesAfterOperations(self, words: list[str]) -> int:
    ans = 0
    count = collections.Counter(''.join(words))
    pairs = sum(value // 2 for value in count.values())

    for length in sorted(len(word) for word in words):
      needPairs = length // 2
      if pairs < needPairs:
        return ans
      ans += 1
      pairs -= needPairs

    return ans