Skip to content

Instantly share code, notes, and snippets.

@cono
Created November 4, 2016 14:47
Show Gist options
  • Save cono/24c15c41f73d26c8d3cfd831286b2d45 to your computer and use it in GitHub Desktop.
Save cono/24c15c41f73d26c8d3cfd831286b2d45 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
# +
# + +
# ++ ++
# ++ ++++
#++++++++
my @heights = qw(1 3 5 1 2 3 4 2);
my $mo = {
left => {
ind => 0,
next => 1
},
right => {
ind => -1,
next => -1
}
};
my ($min, $max) = ('') x 2;
my $prev = 0;
my $sum = 0;
for (@heights) {
my $new_max;
if ($heights[$mo->{left}->{ind}] > $heights[$mo->{right}->{ind}]) {
$new_max = 'left';
$min = 'right';
} else {
$new_max = 'right';
$min = 'left';
}
if ($max ne $new_max) {
$max = $new_max;
$prev = $heights[$mo->{$min}->{ind}];
}
if ($prev > $heights[$mo->{$min}->{ind}]) {
$sum += $prev - $heights[$mo->{$min}->{ind}];
}
$mo->{$min}->{ind} += $mo->{$min}->{next};
}
print "Sum: $sum\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment