Skip to content

Commit 19768f1

Browse files
committed
Fix sequence counting across separated zeros
1 parent abd8055 commit 19768f1

2 files changed

Lines changed: 16 additions & 16 deletions

File tree

src/main/java/interview/MaximumSequenceWithOneZero.java

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package interview;
22

33

4-
import java.util.ArrayList;
54
import java.util.List;
65
import java.util.Objects;
76

@@ -16,24 +15,20 @@ public static int maximumSequenceWithOneZero(List<Integer> b) {
1615
if (b.size() == 1 && b.get(0) == 1) return 1;
1716
if (b.size() == 1 && b.get(0) == 0) return 0;
1817

19-
List<Integer> bytes = new ArrayList<>(b);
2018
int maxCount = 0;
21-
int count = 0;
22-
if (bytes.get(0) == 1) count++;
23-
24-
for (int i = 1; i < bytes.size(); i++) {
25-
if (bytes.get(i) == 1 && bytes.get(i - 1) == 1) {
26-
count++;
27-
}
28-
if (bytes.get(i) == 1 && bytes.get(i - 1) == 0) {
29-
count++;
30-
}
31-
if (bytes.get(i) == 0 && bytes.get(i - 1) == 0) {
32-
maxCount = Math.max(count, maxCount);
33-
count = 0;
19+
int previousCount = 0;
20+
int currentCount = 0;
21+
22+
for (Integer value : b) {
23+
if (value == 1) {
24+
currentCount++;
25+
maxCount = Math.max(maxCount, previousCount + currentCount);
26+
} else {
27+
previousCount = currentCount;
28+
currentCount = 0;
3429
}
3530
}
36-
return Math.max(count, maxCount);
31+
return maxCount;
3732
}
3833

3934

src/test/java/interview/MaximumSequenceWithOneZeroTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ void shouldSplitSequenceOnTwoConsecutiveZeros() {
2828
assertEquals(3, maximumSequenceWithOneZero(List.of(1, 1, 0, 0, 1, 1, 1)));
2929
}
3030

31+
@Test
32+
void shouldNotCountAcrossMultipleSeparatedZeros() {
33+
assertEquals(2, maximumSequenceWithOneZero(List.of(1, 0, 1, 0, 1)));
34+
}
35+
3136
@Test
3237
void shouldCountAllOnesWhenThereIsNoZeroSeparator() {
3338
assertEquals(5, maximumSequenceWithOneZero(List.of(1, 1, 1, 1, 1)));

0 commit comments

Comments
 (0)