For each position in the array, we count how many consecutive 1s start from that position. We scan forward until we hit a 0 or the end of the array, then track the maximum count seen. This straightforward approach checks every possible starting position.
res to 0 to track the maximum consecutive ones.i:cnt to 0.i while the current element is 1, incrementing the counter.0 or reaching the end.res with the maximum of res and cnt.res.We only need one pass through the array. Maintain a running count of consecutive 1s. When we see a 1, increment the count. When we see a 0, compare the current count with the maximum, then reset the count to 0. After the loop, we do one final comparison since the longest sequence might end at the last element.
res and cnt to 0.0, update res with the maximum of res and cnt, then reset cnt to 0.1, increment cnt.res and cnt (to handle sequences ending at the array's end).We can simplify the logic by updating the maximum inside the loop at every step. If we see a 1, we increment the count; otherwise, we reset it to 0. After each element, we update the result. This eliminates the need for a final comparison after the loop.
res and cnt to 0.1, increment cnt.cnt to 0.res to be the maximum of res and cnt.res.When tracking consecutive ones by resetting the counter on encountering a zero, the longest sequence might end at the last element of the array. If you only update the maximum inside the loop when hitting a zero, you will miss this case. Always compare the final count with the result after the loop ends, or update the maximum on every iteration.
A subtle bug is resetting the counter to 1 instead of 0 when encountering a zero, or incrementing before checking the current element. The counter should be reset to 0 when a zero is found, then the next 1 will increment it to 1. Mixing up this logic leads to off-by-one errors in the count.