## 31 December 2014

### Problem:

Given an array of N numbers, you have to make all possible sub-arrays having exactly 3 Numbers. Generate sum of each sub-array. Some "Sum" may occur for more than 1 times. Print the Sum which occured maximum number of times and Print the number of times that sum occured. If more than 1 sum occured for max number of times, print the largest sum

### Input Format:

N-length of array
N lines having array elements

### Output Format:

Maximum occurance of any sum is \$num times and largest such sum is \$sum

n>3

5
1
4
5
3
6

### Sample Output:

Maximum occurance of any sum is 2 times and largest such sum is 12

### Explanations:

(1,5,6)=12 and (4,5,3)=12. All rest sum occurs for 1 time only

Solution:

chomp(\$n=<STDIN>);
for(\$x=0;\$x<\$n;\$x++)
{
chomp(\$tmp=<STDIN>);
push(@arr,\$tmp);
}
%hash;
\$max=0;
\$num=1;
\$check=0;
for(\$i=0;\$i<\$n-2;\$i++)
{
for(\$j=\$i+1;\$j<\$n-1;\$j++)
{
for(\$k=\$j+1;\$k<\$n;\$k++)
{
#print "\$arr[\$i] \$arr[\$j] \$arr[\$k]\n";
\$sum=\$arr[\$i]+\$arr[\$j]+\$arr[\$k];
if(\$check==0)
{
if(\$sum>\$max){\$max=\$sum;}
}
if(\$hash{\$sum})
{
\$check++;
\$hash{\$sum}++;
if(\$num<=\$hash{\$sum})
{
\$num=\$hash{\$sum};
\$max=\$sum;
}
}
else
{
\$hash{\$sum}=1;
}
}
}
}
print "Maximum occurance of any sum is \$num times and largest such sum is \$max";

### Tips:

Take care of condition when each sum occur only 1 time

#### 2 comments:

1. Why don't you use strict and warnings? The tip is misleading: Perl can take care of the the condition itself.

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

<>; # Ignore the first line.
my @in = <>;

my \$win = \$in + \$in + \$in;
my %h = ( \$win => 0 );

for my \$i (0 .. \$#in) {
for my \$j (\$i + 1 .. \$#in) {
for my \$k (\$j + 1 .. \$#in) {
my \$sum = \$in[\$i] + \$in[\$j] + \$in[\$k];
\$h{\$sum}++;
if (\$h{\$sum} > \$h{\$win}
or (\$h{\$sum} == \$h{\$win} and \$sum > \$win)
) {
\$win = \$sum;
}
}
}
}

print "Maximum occurance of any sum is \$h{\$win} times and largest such sum is \$win\n";

2. Thanks for your feedback @E. Choroba... I will use strict and warnings in future posts.
Tip is according to my solution. Anyways, idea is that people should try to solve themselves and then refer sample solution.