Skip to content

Instantly share code, notes, and snippets.

@aklaswad
Created December 6, 2013 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aklaswad/7819657 to your computer and use it in GitHub Desktop.
Save aklaswad/7819657 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
my $PRICE_MAX = 1_000_000;
my @lines = split "\n", do { local $/; <> };
my ( $num_products, undef ) = split( " ", shift(@lines) );
my @prices = splice( @lines, 0, $num_products );
my @hist;
map { $hist[$_]++ } @prices;
my @sorted;
my $sorted_max = 0;
DAY: for my $target ( @lines ) {
my $best = 0;
my $idx = 0;
my $last_val = 0;
my $search_range = $PRICE_MAX;
HEAD: while (1) {
my $val = $sorted[$idx];
unless ( $val ) {
do { $sorted_max++ } while !$hist[$sorted_max] && $sorted_max < $PRICE_MAX;
last HEAD if $sorted_max == $PRICE_MAX;
$val = $sorted[$idx] = $sorted_max;
}
my $tail_target = $target - $val;
last HEAD if $tail_target < $val;
TAIL: for my $gap ( 0..$search_range ) {
if ( $hist[$tail_target - $gap] ) {
if ( $tail_target - $gap != $val || $hist[$val] > 1 ) {
$best = $target - $gap;
last HEAD unless $gap;
$search_range = $gap - 1;
last TAIL;
}
}
}
$idx++;
}
print "$best\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment