in reply to Largest Sum of Consecutive Integers
Update: I was asked in chatter about the -1. Yes, it has a purpose, and were I the instructor I would ding the code for not providing a comment explaining it.#! /usr/bin/perl -w use strict; my @array = @ARGV ? @ARGV : qw(3 2 8 9 -25 5 8 4 4 -3 5 3 -10); my $cur = my $best = my $best_start = my $cur_start = 0; my $best_end = -1; for (0..$#array) { $cur += $array[$_]; if ($cur < 0) { $cur = 0; $cur_start = $_ + 1; } elsif ($best < $cur) { $best = $cur; $best_start = $cur_start; $best_end = $_; } } print qq(Start: $best_start End: $best_end Sum: $best Numbers: @array[$best_start..$best_end] );
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Largest Sum of Consecutive Integers - explanation
by tilly (Archbishop) on Aug 31, 2006 at 18:34 UTC | |
Re^2: Largest Sum of Consecutive Integers (Corrected!)
by BrowserUk (Patriarch) on Aug 31, 2006 at 01:17 UTC | |
Re^2: Largest Sum of Consecutive Integers
by pKai (Priest) on Aug 31, 2006 at 10:15 UTC | |
by tilly (Archbishop) on Aug 31, 2006 at 14:32 UTC | |
Re^2: Largest Sum of Consecutive Integers (abstraction)
by tye (Sage) on Aug 31, 2006 at 17:00 UTC | |
by johnnywang (Priest) on Aug 31, 2006 at 17:53 UTC | |
Re^2: Largest Sum of Consecutive Integers
by OverlordQ (Hermit) on Sep 01, 2006 at 12:19 UTC |