Substring With Largest Variance Problem
Description
LeetCode Problem 2272.
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 <= 10^4sconsists of lowercase English letters.
Solution
Approach: Enumeration + Dynamic Programming
Enumerate an ordered pair of letters a (the more frequent) and b (the less frequent); the variance is the count of a minus the count of b. Scan the string keeping two values: f[0], the number of a since the last b, and f[1], the best variance of a substring ending here that contains at least one b.
- On
a: bothf[0]andf[1]increase by 1. - On
b:f[1] = max(f[1] - 1, f[0] - 1)andf[0] = 0. - Other letters change nothing.
Start f[1] at a very negative value so that a substring without any b is never counted. The answer is the largest f[1] seen.
Complexity: time O(26^2 * n), space O(1).
from itertools import permutations
from math import inf
from string import ascii_lowercase
class Solution:
def largestVariance(self, s: str) -> int:
ans = 0
for a, b in permutations(ascii_lowercase, 2):
f = [0, -inf]
for c in s:
if c == a:
f[0], f[1] = f[0] + 1, f[1] + 1
elif c == b:
f[1] = max(f[1] - 1, f[0] - 1)
f[0] = 0
if ans < f[1]:
ans = f[1]
return ans