Task 1: Consecutive One
"One After Another: Tracking the Longest Streak!"
Given a binary array, find the maximum number of consecutive 1s.
The Strategy: Iterate through the array while maintaining two counters:
current for the length of the ongoing streak of 1s, and best for the maximum length found so far. Reset current to zero whenever a 0 is encountered. Update best whenever current exceeds it.
Perl Implementation
sub consecutive_one {
my (@binary) = @_;
my ($best, $current) = (0, 0);
for my $bit (@binary) {
if ($bit == 1) {
$current++;
$best = $current if $current > $best;
} else {
$current = 0;
}
}
return $best;
}
Python Implementation
def consecutive_one(binary: list[int]) -> int:
best = current = 0
for bit in binary:
if bit == 1:
current += 1
best = max(best, current)
else:
current = 0
return best