use strict; use warnings; use feature 'say'; use List::Util 'min'; my @strs = ( '0' x 1_000_000, '01' x 1_000_000, '011' x 1_000_000, '0110' x 1_000_000, ); for (@strs) { my $l = length(tr/01//sr); my $d = length() - $l; say $l + min( $d, 2 ); }