The weekly challenge 218 - Task 1: Maximum Product

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-218/#TASK1
 3 #
 4 # Task 1: Maximum Product
 5 # =======================
 6 #
 7 # You are given a list of 3 or more integers.
 8 #
 9 # Write a script to find the 3 integers whose product is the maximum and return it.
10 #
11 ## Example 1
12 ##
13 ## Input: @list = (3, 1, 2)
14 ## Output: 6
15 ##
16 ## 1 x 2 x 3 => 6
17 #
18 ## Example 2
19 ##
20 ## Input: @list = (4, 1, 3, 2)
21 ## Output: 24
22 ##
23 ## 2 x 3 x 4 => 24
24 #
25 ## Example 3
26 ##
27 ## Input: @list = (-1, 0, 1, 3, 1)
28 ## Output: 3
29 ##
30 ## 1 x 1 x 3 => 3
31 #
32 ## Example 4
33 ##
34 ## Input: @list = (-8, 2, -9, 0, -4, 3)
35 ## Output: 216
36 ##
37 ## -9 × -8 × 3 => 216
38 #
39 ############################################################
40 ##
41 ## discussion
42 ##
43 ############################################################
44 #
45 # Using 3 index variables i, j, k we walk the list from
46 # beginning to end, calculate the product at the current
47 # 3 index positions, and then return the maximum
48 
49 use strict;
50 use warnings;
51 
52 maximum_product(3, 1, 2);
53 maximum_product(4, 1, 3, 2);
54 maximum_product(-1, 0, 1, 3, 1);
55 maximum_product(-8, 2, -9, 0, -4, 3);
56 
57 sub maximum_product {
58    my @list = @_;
59    my $maximum;
60    print "Input: (" . join(", ", @list) . ")\n";
61    foreach my $i (0..$#list-2) {
62       foreach my $j ($i+1..$#list-1) {
63          foreach my $k ($j+1..$#list) {
64             my $prod = $list[$i] * $list[$j] * $list[$k];
65             $maximum //= $prod;
66             $maximum = $prod if $prod > $maximum;
67          }
68       }
69    }
70    print "Output: $maximum\n";
71 }
72