forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubstring With Largest Variance.cpp
37 lines (36 loc) · 1.07 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
/*
Time: O(26*26*n)
Space: O(1)
Tag: Kadane's Algorithm
Difficulty: H (Logic) | E(Implementation)
*/
class Solution {
public:
int largestVariance(string s) {
int res = 0;
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
if (i == j) continue;
int highFreq = 0;
int lowFreq = 0;
bool prevHadLowFreqChar = false;
for (char ch : s) {
if (ch - 'a' == i)
highFreq++;
else if (ch - 'a' == j)
lowFreq++;
if (lowFreq > 0)
res = max(res, highFreq - lowFreq);
else if (prevHadLowFreqChar)
res = max(res, highFreq - 1);
if (highFreq - lowFreq < 0) {
highFreq = 0;
lowFreq = 0;
prevHadLowFreqChar = true;
}
}
}
}
return res;
}
};