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:
1
💡 Note:
The substring "a" has a=1 occurrences while b=0 occurrences, giving variance 1-0=1. Similarly for other single character substrings with respect to any other character.
Example 3 — Two Characters
$
Input:
s = "aab"
›
Output:
2
💡 Note:
The substring "aa" has a=2 occurrences while b=0 occurrences, giving variance 2-0=2. This is the maximum variance possible.
Constraints
- 1 ≤ s.length ≤ 104
- s consists of lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code