#!/usr/bin/env perl
use strict;
use warnings;

use List::Util qw(min max);

my $invalid = `./sol1.pl input`; # cheers
die "$!" if $?;

my @nums;
{
    local $/;
    open(my $fh, '<', 'input') or die "$!";
    @nums = split("\n", <$fh>);
}

# IDEA: caterpillar slide
#   - inch front forward until > invalid
#   - inch back forward until < invalid
# if at any point = invalid, we win
my $sum = 0;
my @mem;

print "GOAL: $invalid\n";
for my $n (@nums) {
    printf "DBG> n: %d, sum: %d, wind: %d\n", $n, $sum, scalar @mem;
    if ($sum == $invalid) {
        my $result = min(@mem) + max(@mem);
        print "$result\n";
        exit 0;
    } 

    # move that butt forward until we can add $n without overflowing
    while (($sum + $n) > $invalid) {
        $sum -= shift(@mem);
        if (!@mem) {
            # impossible, too big
            exit(1);
        }
    }
    # scooch forward!
    $sum += $n;
    push(@mem, $n);
}

exit 1;
