-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximize Number of 1s.cpp
More file actions
76 lines (68 loc) · 2.06 KB
/
Maximize Number of 1s.cpp
File metadata and controls
76 lines (68 loc) · 2.06 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
//============================================================================
// Name : Maximize Number of 1s.cpp
// Author : SidPro
// Version : 1.0
// Description :
/*
Maximize Number of 1's
Given a binary array arr of size N and an integer M. Find the maximum number of consecutive 1's produced by flipping at most M 0's.
*/
//============================================================================
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// m is maximum of number zeroes allowed to flip
// n is size of array
int findZeroes(int arr[], int n, int m) {
// code here
// Left and right indexes of current window
int wL = 0, wR = 0;
// Left index and size of the widest window
int bestL = 0, bestWindow = 0;
// Count of zeroes in current window
int zeroCount = 0;
// While right boundary of current window doesn't cross
// right end
while (wR < n){
// If zero count of current window is less than m,
// widen the window toward right
if (zeroCount <= m){
if (arr[wR] == 0)zeroCount++;
wR++;
}
// If zero count of current window is more than m,
// reduce the window from left
if (zeroCount > m){
if (arr[wL] == 0)zeroCount--;
wL++;
}
// Updqate widest window if this window size is more
if ((wR-wL > bestWindow) && (zeroCount<=m)){
bestWindow = wR-wL;
bestL = wL;
}
}
return bestWindow;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, i, m;
cin >> n;
int arr[n];
for (i = 0; i < n; i++) {
cin >> arr[i];
}
cin >> m;
Solution ob;
auto ans = ob.findZeroes(arr, n, m);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends