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 = (); map {$p{$_} = $n{$_}}(sort {$n{$b} <=> $n{$a}} keys %n)[0..1]; } print $p{(sort {$p{$b} <=> $p{$a}} keys %p)[0]};