-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum_of_integers.pl
49 lines (44 loc) · 1.27 KB
/
sum_of_integers.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
####################################################
# script name : sum_of_integers.pl
# description : print sum of largest sum of contiguous integers in a list
# author : Dai Nguyen-Van
# email : dainv1989@gmail.com
# creation date : 21/10/2013
####################################################
#!/usr/bin/perl
# open file in read-only mode
# read content of input file
# remove all end of line character (EOL)
open (DATA, "<", $ARGV[0]) or die $!;
@content = <DATA>;
chomp(@content);
foreach (@content)
{
if($_ ne "")
{
my $largest_sum = -2147483648;
# remove all whitespace
$_ =~ s/\s//g;
my @numbers = split(",",$_);
# sum of total integers
for (my $i = $#numbers; $i >= 0; $i--)
{
for (my $j = 0; $j <= $i; $j++)
{
# calculate sum of sub-array from jth to ith integers
my $sum = 0;
for (my $k = $j ; $k <= $i; $k++)
{
$sum += $numbers[$k];
}
# re-calculate largest sum
if ($sum > $largest_sum)
{
$largest_sum = $sum;
}
}
}
print "$largest_sum\n";
}
}
close DATA;