-
Notifications
You must be signed in to change notification settings - Fork 0
/
Alternating Groups II.cpp
50 lines (40 loc) · 1.14 KB
/
Alternating Groups II.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
47
48
49
50
#include <vector>
class Solution {
public:
int numberOfAlternatingGroups(std::vector<int>& colors, int k) {
int n = colors.size();
if (k > n) return 0;
int count = 0;
bool check = true;
for (int i = 0; i < k - 1; ++i) {
if (colors[i] == colors[i + 1]) {
check = false;
break;
}
}
if (check) {
++count;
}
for (int i = 1; i < n; ++i) {
int last = i - 1;
int first = (i + k - 1) % n;
if (check) {
if (colors[last] == colors[(last + 1) % n] || colors[first] == colors[(first - 1 + n) % n]) {
check = false;
}
} else {
check = true;
for (int j = i; j < i + k - 1; ++j) {
if (colors[j % n] == colors[(j + 1) % n]) {
check = false;
break;
}
}
}
if (check) {
++count;
}
}
return count;
}
};