use strict; use warnings; my @nums = split '', <>; my $n = $#nums+1; my @dp; for my $i (0..(1<<$n)-1){ $dp[$i] = [0, $n]; } my(@nd, $val, @pos); my @ans = (0); for my $d (0..(1<<$n)-1){ next if($dp[$d][1] < 3); for my $i (0..$n-1){ next if(($d>>$i) % 2); $nd[0] = $d | 1<<$i; $dp[$nd[0]][1] = $dp[$d][1]-1; if($i < $n-1-1){ for my $j ($i+1..$n-1){ next if(($nd[0]>>$j) % 2); $nd[1] = $nd[0] | 1<<$j; $dp[$nd[1]][1] = $dp[$nd[0]][1]-1; if($j < $n-1){ for my $k ($j+1..$n-1){ next if(($nd[1]>>$k) % 2); $nd[2] = $nd[1] | 1<<$k; $dp[$nd[2]][1] = $dp[$nd[1]][1]-1; @pos = map {$n-1 - $_} ($i, $j, $k); if(0 < $nums[$pos[2]] and $nums[$pos[2]] != $nums[$pos[1]] and $nums[$pos[1]] == $nums[$pos[0]]){ $val = $nums[$pos[2]].$nums[$pos[1]].$nums[$pos[0]] + $dp[$d][0]; if($dp[$nd[2]][0] < $val){ $dp[$nd[2]][0] = $val; push @ans, $val; } } } } } } } } print+(sort {$b <=> $a} @ans)[0];