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
N lines having array elements
Output Format:
Maximum occurance of any sum is $num times and largest such sum is $sumConstraints:
n>3Sample Input
5
1
4
5
3
6
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:
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
Why don't you use strict and warnings? The tip is misleading: Perl can take care of the the condition itself.
ReplyDelete#!/usr/bin/perl
use warnings;
use strict;
<>; # Ignore the first line.
my @in = <>;
my $win = $in[0] + $in[1] + $in[2];
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";
Thanks for your feedback @E. Choroba... I will use strict and warnings in future posts.
ReplyDeleteTip is according to my solution. Anyways, idea is that people should try to solve themselves and then refer sample solution.