2272.cpp (771B)
1 class Solution { 2 public: 3 int largestVariance(const string &s) { 4 int count[27] = {0}, res = 0; 5 for (char c : s) 6 count[c & 0xF]++; 7 8 for (char ma = 'a'; ma <= 'z'; ma++) { 9 for (char mi = 'a'; mi <= 'z'; mi++) { 10 if (ma == mi || !count[ma & 0xF] || !count[mi & 0xF]) continue; 11 int mac = 0, mic = 0, rst = count[mi & 0xF]; 12 for (char c : s) { 13 if (c == ma) 14 mac++; 15 else if (c == mi) 16 mic++, rst--; 17 18 if (mic > 0) res = max(res, mac - mic); 19 if (mac < mic && rst > 0) mac = mic = 0; 20 } 21 } 22 } 23 return res; 24 } 25 };