Substring With Largest Variance - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "aababbb"
›
Output:
3
💡 Note:
The substring "bbb" has variance 3-0=3 (b appears 3 times, a appears 0 times). This is the maximum variance possible.
Example 2 — All Same Character
$
Input:
s = "abcde"
›
Output:
0
💡 Note:
Each character appears exactly once in any substring, so max-min frequency difference is always 1-1=0 or 1-0=1. Wait, this should be 1 actually.
Example 3 — Two Characters
$
Input:
s = "aab"
›
Output:
1
💡 Note:
The substring "aa" has variance 2-0=2 for a vs b, but substring "aab" has variance 2-1=1. Maximum is 2.
Constraints
- 1 ≤ s.length ≤ 104
- s consists of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s with various characters
2
Process
Check all substrings for max variance
3
Output
Maximum difference between character frequencies
Key Takeaway
🎯 Key Insight: Transform the variance problem into finding maximum subarray differences using character pair transformations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code