The weekly challenge 304 - Task 2: Maximum Average
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-304/#TASK2 3 # 4 # Task 2: Maximum Average 5 # ======================= 6 # 7 # You are given an array of integers, @ints and an integer, $n which is less 8 # than or equal to total elements in the given array. 9 # 10 # Write a script to find the contiguous subarray whose length is the given 11 # integer, $n, and has the maximum average. It should return the average. 12 # 13 ## Example 1 14 ## 15 ## Input: @ints = (1, 12, -5, -6, 50, 3), $n = 4 16 ## Output: 12.75 17 ## 18 ## Subarray: (12, -5, -6, 50) 19 ## Average: (12 - 5 - 6 + 50) / 4 = 12.75 20 # 21 ## Example 2 22 ## 23 ## Input: @ints = (5), $n = 1 24 ## Output: 5 25 # 26 ############################################################ 27 ## 28 ## discussion 29 ## 30 ############################################################ 31 # 32 # We calculate the average of the first n numbers. Then, using 33 # each element of the array as the starting point, we calculate 34 # the average starting at that point (skipping sub-arrays that 35 # aren't big enough at the end). Out of all of these averages, 36 # we keep the maximum. 37 38 use strict; 39 use warnings; 40 use List::Util qw(sum); 41 42 maximum_average(4, 1, 12, -5, -6, 50, 3); 43 maximum_average(1, 5); 44 45 sub maximum_average { 46 my ($n, @ints) = @_; 47 if($n > scalar(@ints) ) { 48 return print "Error: not enough elements in list!\n"; 49 } 50 print "Input: n=$n, \@ints=(" . join(", ", @ints) . ")\n"; 51 my $max = sum(@ints[0..$n-1]) / $n; 52 foreach my $i (1..$#ints) { 53 last if $i+$n-1 > $#ints; 54 my $avg = sum(@ints[$i..$i+$n-1]) / $n; 55 $max = $avg if $avg > $max; 56 } 57 print "Output: $max\n"; 58 }