my $count = 0; my $lastCount = 0; my $totalValleys = 0; my $line1 = <>; my $line2 = <>; @steps = split('', $line2); foreach (@steps) { s/U/\+1\n/g; s/D/\-1\n/g; $lastCount = $count; $count = $count + $_; if ( $count == 0 and $lastCount < 0 ) { $totalValleys++; } } print $totalValleys;