use strict; use warnings; my $num = ; my %sushi; for(reverse split(' ', )){ $sushi{$num} = $_; $num--; } my %p = (-1 => 0); my %n = %p; for my $i (sort {$a <=> $b} keys %sushi) { for my $j (keys %p) { if($i - $j != 1){ if(!defined($n{$i}) or (defined($n{$i}) and $n{$i} < $p{$j} + $sushi{$i})){ $n{$i} = $p{$j} + $sushi{$i}; } } } %p = %n; } print $p{(sort {$p{$b} <=> $p{$a}} keys %p)[0]};