classSolution { public: intlargestVariance(string s){ int ans = 0; unordered_set<char> unique(s.begin(), s.end()); // go through each possibilities to find the ans. for (char a : unique) for (char b : unique) { if (a == b) continue; int var = 0, has_b = 0, first_b = 0; for (auto ch : s) { // var is used to track the occurrences diff between "a" and "b". if (ch == a) ++var; elseif (ch == b) { has_b = true; // we are having a leading "b" and now one more "b" with cnt(a) >= cnt(b), // so we can cut the leading "b" for a better ans. if (first_b && var >= 0) first_b = false; // "--var < 0" indicates that we are having too many "b(s)" here, // so we take this "b" as a fresh start. elseif (--var < 0) first_b = true, var = -1; } // update the ans if and only if "b" is within the substr. ans = max(ans, has_b ? var : 0); } } return ans; } };