Skip to content

Commit 403b04b

Browse files
author
Tushar Roy
committed
flip 0s to get max consecutive 1s in array
1 parent b51e69a commit 403b04b

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

python/array/flip0smaximum1s.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# http://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
2+
3+
def flip_0s_to_maximize_consecutive_1s(input, flips_allowed):
4+
window_start = 0
5+
count_zero = 0
6+
result = 0
7+
for i in range(len(input)):
8+
if input[i] == 1:
9+
result = max(result, i - window_start + 1)
10+
else:
11+
if count_zero < flips_allowed:
12+
count_zero = count_zero + 1
13+
else:
14+
while True:
15+
if input[window_start] == 0:
16+
window_start = window_start + 1
17+
break
18+
window_start = window_start + 1
19+
return result
20+
21+
if __name__ == '__main__':
22+
input = [0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1]
23+
print(flip_0s_to_maximize_consecutive_1s(input, 1))
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.interview.array;
2+
3+
/**
4+
* Date 12/29/2015
5+
* @author Tushar Roy
6+
*
7+
* Given input array of 0s and 1s and number of flips allowed from 0 to 1, what is maximum consecutive 1s we can have
8+
* in array
9+
*
10+
* Time complexity - O(n)
11+
* Space complexity - O(1)
12+
*
13+
* http://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
14+
*/
15+
public class Flip0sMaximum1s {
16+
17+
public int flip0sToMaximizeConsecutive1s(int input[], int flipsAllowed) {
18+
19+
int windowStart = 0;
20+
int countZero = 0;
21+
int result = 0;
22+
for (int i = 0 ; i < input.length; i++) {
23+
if (input[i] == 1) {
24+
result = Math.max(result, i - windowStart + 1);
25+
} else {
26+
if (countZero < flipsAllowed) {
27+
countZero++;
28+
} else {
29+
while(true) {
30+
if (input[windowStart] == 0) {
31+
windowStart++;
32+
break;
33+
}
34+
windowStart++;
35+
}
36+
}
37+
}
38+
}
39+
return result;
40+
}
41+
42+
public static void main(String args[]) {
43+
int input[] = {0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1};
44+
Flip0sMaximum1s fm = new Flip0sMaximum1s();
45+
System.out.print(fm.flip0sToMaximizeConsecutive1s(input, 1));
46+
}
47+
}

0 commit comments

Comments
 (0)