-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathContinuous_Seq.cpp
119 lines (103 loc) · 2.47 KB
/
Continuous_Seq.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// C++ program to find index of zero
// to be replaced by one to get longest
// continuous sequence of ones.
#include <bits/stdc++.h>
using namespace std;
// Returns index of 0 to be replaced
// with 1 to get longest continuous
// sequence of 1s. If there is no 0
// in array, then it returns -1.
int maxOnesIndex(bool arr[], int n)
{
// To store starting point of
// sliding window.
int start = 0;
// To store ending point of
// sliding window.
int end = 0;
// Index of zero with maximum number
// of ones around it.
int maxIndex = -1;
// Index of last zero element seen
int lastInd = -1;
// Count of ones if zero at index
// maxInd is replaced by one.
int maxCnt = 0;
while (end < n) {
// Keep increasing ending point
// of sliding window until one is
// present in input array.
while (end < n && arr[end]) {
end++;
}
// If this is not first zero element
// then number of ones obtained by
// replacing zero at lastInd is
// equal to length of window.
// Compare this with maximum number
// of ones in a previous window so far.
if (maxCnt < end - start && lastInd != -1) {
maxCnt = end - start;
maxIndex = lastInd;
}
// The new starting point of next window
// is from index position next to last
// zero which is stored in lastInd.
start = lastInd + 1;
lastInd = end;
end++;
}
// For the case when only one zero is
// present in input array and is at
// last position.
if (maxCnt < end - start && lastInd != -1) {
maxCnt = end - start;
maxIndex = lastInd;
}
return maxIndex;
}
// Driver function
int main()
{
// bool arr[] = {1, 1, 1, 1, 0};
int i,NoOfElements;
int *arr;
cout<<"How many elements? Enter the size: ";
cin>>NoOfElements;
if (arr==NULL)
{
cout<<"Array is empty";
return 1;
}
// store input from user to array
cout<<"Enter numbers\n";
for (int i = 0; i < NoOfElements; ++i) {
cin >> arr[i];
}
cout << "The numbers are:\n ";
// print array elements
for (int n = 0; n < NoOfElements; ++n) {
cout << arr[n] << " ";
}
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Index of 0 to be replaced is "<< maxOnesIndex(arr, n);
return 0;
}
/*
Time Complexity: O(n)
Space Complexity: O(1)
Test Case:
Input:
How many elements? Enter the size:
5
Enter numbers
1
1
1
1
0
Output:
The numbers are:
1 1 1 1 0
Index of 0 to be replaced is 4
*/