in reply to Puzzle: Given an array of integers, find the best sequence of pop / shift...

#! /usr/bin/perl -w use strict; my @numbers = @ARGV ? @ARGV : qw(2 8 4 5); # Scores is a 2-dim array, $scores[$i][$j] is the best score # that you can get given a string of $j numbers starting at # $numbers[$i]. my @scores; for (0..$#numbers) { $scores[$_][1] = $numbers[$_]; } for my $j (2..@numbers) { for my $i (0..(@numbers - $j)) { my $a = $numbers[$i] - $scores[$i+1][$j-1]; my $b = $numbers[$i+$j-1] - $scores[$i][$j-1]; $scores[$i][$j] = ($a > $b) ? $a : $b; } } my $i = 0; for my $j (reverse 1..$#numbers) { if ($numbers[$i] - $scores[$i+1][$j] > $numbers[$i+$j] - $scores[$i] +[$j]) { print "shift $numbers[$i]\n"; $i++; } else { print "pop $numbers[$i+$j]\n"; } } print "shift $numbers[$i]\n\n"; print "Best score: $scores[0][scalar @numbers]\n";
UPDATE: Corrected conditional in the print so I print out the solution I calculated.
  • Comment on Re: Puzzle: Given an array of integers, find the best sequence of pop / shift...
  • Download Code