forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximize-the-number-of-partitions-after-operations.cpp
46 lines (44 loc) · 1.57 KB
/
maximize-the-number-of-partitions-after-operations.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
43
44
45
46
// Time: O(n)
// Space: O(n)
// prefix sum, greedy
class Solution {
public:
int maxPartitionsAfterOperations(string s, int k) {
vector<int> left(size(s) + 1);
vector<int> left_mask(size(s) + 1);
for (int i = 0, cnt = 0, mask = 0; i < size(s); ++i) {
mask |= 1 << (s[i] - 'a');
if (__builtin_popcount(mask) > k) {
++cnt;
mask = 1 << (s[i] - 'a');
}
left[i + 1] = cnt;
left_mask[i + 1] = mask;
}
vector<int> right(size(s) + 1);
vector<int> right_mask(size(s) + 1);
for (int i = size(s) - 1, cnt = 0, mask = 0; i >= 0; --i) {
mask |= 1 << (s[i] - 'a');
if (__builtin_popcount(mask) > k) {
++cnt;
mask = 1 << (s[i] - 'a');
}
right[i] = cnt;
right_mask[i] = mask;
}
int result = 0;
for (int i = 0; i < size(s); ++i) {
int curr = left[i] + right[i + 1];
const int mask = left_mask[i] | right_mask[i + 1];
if (__builtin_popcount(left_mask[i]) == k && __builtin_popcount(right_mask[i + 1]) == k && __builtin_popcount(mask) != 26) {
curr += 3;
} else if (__builtin_popcount(mask) + (__builtin_popcount(mask) != 26 ? 1 : 0) > k) { // test case: s = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", k = 26
curr += 2;
} else {
curr += 1;
}
result = max(result, curr);
}
return result;
}
};