How to resolve the algorithm Greatest subsequential sum step by step in the Perl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Greatest subsequential sum step by step in the Perl programming language
Table of Contents
Problem Statement
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Greatest subsequential sum step by step in the Perl programming language
Source code in the perl programming language
use strict;
sub max_sub(\@) {
my ($a, $maxs, $maxe, $s, $sum, $maxsum) = shift;
foreach (0 .. $#$a) {
my $t = $sum + $a->[$_];
($s, $sum) = $t > 0 ? ($s, $t) : ($_ + 1, 0);
if ($maxsum < $sum) {
$maxsum = $sum;
($maxs, $maxe) = ($s, $_ + 1)
}
}
@$a[$maxs .. $maxe - 1]
}
my @a = map { int(rand(20) - 10) } 1 .. 10;
my @b = (-1) x 10;
print "seq: @a\nmax: [ @{[max_sub @a]} ]\n";
print "seq: @b\nmax: [ @{[max_sub @b]} ]\n";
use strict;
my @a = (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1);
my @maxsubarray;
my $maxsum = 0;
foreach my $begin (0..$#a) {
foreach my $end ($begin..$#a) {
my $sum = 0;
$sum += $_ foreach @a[$begin..$end];
if($sum > $maxsum) {
$maxsum = $sum;
@maxsubarray = @a[$begin..$end];
}
}
}
print "@maxsubarray\n";
You may also check:How to resolve the algorithm Check output device is a terminal step by step in the Perl programming language
You may also check:How to resolve the algorithm Walk a directory/Non-recursively step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Comments step by step in the Java programming language
You may also check:How to resolve the algorithm Add a variable to a class instance at runtime step by step in the ooRexx programming language
You may also check:How to resolve the algorithm Repeat step by step in the Nim programming language