File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ // C++ program to calculate maximum contiguous
2
+ // ones in string
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+
6
+ // function to calculate maximum contiguous ones
7
+ int maxContiguousOnes (string s, int k)
8
+ {
9
+
10
+ int i, j, a, b, count;
11
+
12
+ // multiset is used to store frequency of
13
+ // 1's of each portion of contiguous 1 in
14
+ // string in decreasing order
15
+ multiset<int , greater<int > > m;
16
+
17
+ // this loop calculate all the frequency
18
+ // and stores them in multiset
19
+ for (i = 0 ; i < s.length (); i++) {
20
+ if (s[i] == ' 1' ) {
21
+ count = 0 ;
22
+ j = i;
23
+ while (s[j] == ' 1' && j < s.length ()) {
24
+ count++;
25
+ j++;
26
+ }
27
+ m.insert (count);
28
+ i = j - 1 ;
29
+ }
30
+ }
31
+
32
+ // if their is no 1 in string, then return 0
33
+ if (m.size () == 0 )
34
+ return 0 ;
35
+
36
+ // calculates maximum contiguous 1's on
37
+ // doing rotations
38
+ while (k > 0 && m.size () != 1 ) {
39
+
40
+ // Delete largest two elements
41
+ a = *(m.begin ());
42
+ m.erase (m.begin ());
43
+ b = *(m.begin ());
44
+ m.erase (m.begin ());
45
+
46
+ // insert their sum back into the multiset
47
+ m.insert (a + b);
48
+ k--;
49
+ }
50
+
51
+ // return maximum contiguous ones
52
+ // possible after k rotations
53
+ return *(m.begin ());
54
+ }
55
+
56
+ // Driver code
57
+ int main ()
58
+ {
59
+ string s = " 10011110011" ;
60
+ int k = 1 ;
61
+ cout << maxContiguousOnes (s, k);
62
+ return 0 ;
63
+ }
64
+
You can’t perform that action at this time.
0 commit comments