2272. Substring With Largest Variance
Description
The variance of a string is defined as the largest difference between the number of occurrences of any 2
characters present in the string. Note the two characters may or may not be the same.
Given a string s
consisting of lowercase English letters only, return the largest variance possible among all substrings of s
.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aababbb" Output: 3 Explanation: All possible variances along with their respective substrings are listed below: - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb". - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab". - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb". - Variance 3 for substring "babbb". Since the largest possible variance is 3, we return it.
Example 2:
Input: s = "abcde" Output: 0 Explanation: No letter occurs more than once in s, so the variance of every substring is 0.
Constraints:
1 <= s.length <= 104
s
consists of lowercase English letters.
Solutions
Solution 1: Enumeration + Dynamic Programming
Since the character set only contains lowercase letters, we can consider enumerating the most frequent character \(a\) and the least frequent character \(b\). For a substring, the difference in the number of occurrences of these two characters is the variance of the substring.
Specifically, we use a double loop to enumerate \(a\) and \(b\). We use \(f[0]\) to record the number of consecutive occurrences of character \(a\) ending at the current character, and \(f[1]\) to record the variance of the substring ending at the current character and containing both \(a\) and \(b\). We iterate to find the maximum value of \(f[1]\).
The recurrence formula is as follows:
- If the current character is \(a\), then both \(f[0]\) and \(f[1]\) are incremented by \(1\);
- If the current character is \(b\), then \(f[1] = \max(f[1] - 1, f[0] - 1)\), and \(f[0] = 0\);
- Otherwise, no need to consider.
Note that initially setting \(f[1]\) to a negative maximum value ensures that updating the answer is valid.
The time complexity is \(O(n \times |\Sigma|^2)\), where \(n\) is the length of the string, and \(|\Sigma|\) is the size of the character set. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
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 |
|
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 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|