forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
substring-with-largest-variance.cpp
42 lines (40 loc) · 1.41 KB
/
substring-with-largest-variance.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Time: O(a^2 * n), a is the size of alphabets
// Space: O(a)
// kadane's algorithm
class Solution {
public:
int largestVariance(string s) {
const auto& modified_kadane = [&s](const auto& x, const auto& y) {
int result = 0;
vector<int> lookup(2);
vector<int> remain = {static_cast<int>(count(cbegin(s), cend(s), x)),
static_cast<int>(count(cbegin(s), cend(s), y))};
int curr = 0;
for (const auto& c : s) {
if (!(c == x || c == y)) {
continue;
}
lookup[c != x] = 1;
--remain[c != x];
curr += (c == x) ? 1 : -1;
if (curr < 0 && remain[0] && remain[1]) {
curr = lookup[0] = lookup[1] = 0; // reset states if the remain has both x, y
}
if (lookup[0] && lookup[1]) {
result = max(result, curr); // update result if x, y both exist
}
}
return result;
};
unordered_set<char> alphabets(cbegin(s), cend(s));
int result = 0;
for (const auto& x : alphabets) {
for (const auto& y: alphabets) {
if (x != y) {
result = max(result, modified_kadane(x, y));
}
}
}
return result;
}
};