Skip to content

1781. Sum of Beauty of All Substrings 👍

  • Time: $O(n^2)$
  • Space: $O(26) = O(1)$
 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
class Solution {
 public:
  int beautySum(string s) {
    int ans = 0;

    for (int i = 0; i < s.length(); ++i) {
      vector<int> count(26);
      for (int j = i; j < s.length(); ++j) {
        ++count[s[j] - 'a'];
        ans += ranges::max(count) - getMinFreq(count);
      }
    }

    return ans;
  }

 private:
  // Returns the minimum frequency > 0.
  int getMinFreq(const vector<int>& count) {
    int minFreq = INT_MAX;
    for (const int freq : count)
      if (freq > 0)
        minFreq = min(minFreq, freq);
    return minFreq;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int beautySum(String s) {
    int ans = 0;

    for (int i = 0; i < s.length(); ++i) {
      int[] count = new int[26];
      for (int j = i; j < s.length(); ++j) {
        ++count[s.charAt(j) - 'a'];
        ans += Arrays.stream(count).max().getAsInt() - getMinFreq(count);
      }
    }

    return ans;
  }

  // Returns the minimum frequency > 0.
  private int getMin(int[] count) {
    int minFreq = Integer.MAX_VALUE;
    for (final int freq : count)
      if (freq > 0)
        minFreq = min(minFreq, freq);
    return minFreq;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def beautySum(self, s: str) -> int:
    ans = 0

    for i in range(len(s)):
      count = collections.Counter()
      for j in range(i, len(s)):
        count[s[j]] += 1
        ans += max(count.values()) - min(count.values())

    return ans