# Codingame Solution: Create the longest sequence of 1s

Original Problem

## Goal

Given some bitstring b, you may change one bit from a 0 to a 1 in order to create the longest possible sequence of consecutive 1s. Output the length of the resulting longest sequence.

Example: 11011101111
Flipping the second 0 results in 11011111111, where the longest sequence of 1s is 8 long.

Input
Line 1: The bitstring b
Output
Line 1: The length of the longest possible sequence of 1s after flipping one bit
Constraints
0 < number of bits in b < 1000
b contains at least one 0

## Solution

When we walk through the binary string, character by character, we count the number of 1s until we encounter a 0. We then reset the current count, but use it as the count of the previous block if the next bit is a 1. After that we search for the maximum sum of the current and previous block, separated only by one 0. The final result is then this maximum plus the one, the bit we flipped from 0 to 1. An implementation can then look as follows

```const b = readline();

let cur = 0, pre = 0, max = 0;

for (let i = 0; i < b.length; i++) {

if (b[i] === '1') {
cur++;
} else {
pre = b[i + 1] !== '1' ? 0 : cur;
cur = 0;
}
max = Math.max(pre + cur, max);
}

print(max + 1);```

« Back to problem overview