Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 11 additions & 16 deletions src/main/java/interview/MaximumSequenceWithOneZero.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package interview;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

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

List<Integer> bytes = new ArrayList<>(b);
int maxCount = 0;
int count = 0;
if (bytes.get(0) == 1) count++;

for (int i = 1; i < bytes.size(); i++) {
if (bytes.get(i) == 1 && bytes.get(i - 1) == 1) {
count++;
}
if (bytes.get(i) == 1 && bytes.get(i - 1) == 0) {
count++;
}
if (bytes.get(i) == 0 && bytes.get(i - 1) == 0) {
maxCount = Math.max(count, maxCount);
count = 0;
int previousCount = 0;
int currentCount = 0;

for (Integer value : b) {
if (value == 1) {
currentCount++;
maxCount = Math.max(maxCount, previousCount + currentCount);
} else {
previousCount = currentCount;
currentCount = 0;
}
}
return Math.max(count, maxCount);
return maxCount;
}


Expand Down
5 changes: 5 additions & 0 deletions src/test/java/interview/MaximumSequenceWithOneZeroTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ void shouldSplitSequenceOnTwoConsecutiveZeros() {
assertEquals(3, maximumSequenceWithOneZero(List.of(1, 1, 0, 0, 1, 1, 1)));
}

@Test
void shouldNotCountAcrossMultipleSeparatedZeros() {
assertEquals(2, maximumSequenceWithOneZero(List.of(1, 0, 1, 0, 1)));
}

@Test
void shouldCountAllOnesWhenThereIsNoZeroSeparator() {
assertEquals(5, maximumSequenceWithOneZero(List.of(1, 1, 1, 1, 1)));
Expand Down