-
Notifications
You must be signed in to change notification settings - Fork 16
/
max-con-1-rotate-binary.cpp
64 lines (53 loc) · 1.48 KB
/
max-con-1-rotate-binary.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
51
52
53
54
55
56
57
58
59
60
61
62
63
// C++ program to calculate maximum contiguous
// ones in string
#include <bits/stdc++.h>
using namespace std;
// function to calculate maximum contiguous ones
int maxContiguousOnes(string s, int k)
{
int i, j, a, b, count;
// multiset is used to store frequency of
// 1's of each portion of contiguous 1 in
// string in decreasing order
multiset<int, greater<int> > m;
// this loop calculate all the frequency
// and stores them in multiset
for (i = 0; i < s.length(); i++) {
if (s[i] == '1') {
count = 0;
j = i;
while (s[j] == '1' && j < s.length()) {
count++;
j++;
}
m.insert(count);
i = j - 1;
}
}
// if their is no 1 in string, then return 0
if (m.size() == 0)
return 0;
// calculates maximum contiguous 1's on
// doing rotations
while (k > 0 && m.size() != 1) {
// Delete largest two elements
a = *(m.begin());
m.erase(m.begin());
b = *(m.begin());
m.erase(m.begin());
// insert their sum back into the multiset
m.insert(a + b);
k--;
}
// return maximum contiguous ones
// possible after k rotations
return *(m.begin());
}
// Driver code
int main()
{
string s = "10011110011";
int k = 1;
cout << maxContiguousOnes(s, k);
return 0;
}