perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 339 - Task 1: Max Diff

  1 #!/usr/bin/env perl
  2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-339/#TASK1
  3 #
  4 # Task 1: Max Diff
  5 # ================
  6 #
  7 # You are given an array of integers having four or more elements.
  8 #
  9 # Write a script to find two pairs of numbers from this list (four numbers
 10 # total) so that the difference between their products is as large as possible.
 11 #
 12 # In the end return the max difference.
 13 #
 14 ## With Two pairs (a, b) and (c, d), the product difference is (a * b) - (c * d).
 15 #
 16 #
 17 ## Example 1
 18 ##
 19 ## Input: @ints = (5, 9, 3, 4, 6)
 20 ## Output: 42
 21 ##
 22 ## Pair 1: (9, 6)
 23 ## Pair 2: (3, 4)
 24 ## Product Diff: (9 * 6) - (3 * 4) => 54 - 12 => 42
 25 #
 26 #
 27 ## Example 2
 28 ##
 29 ## Input: @ints = (1, -2, 3, -4)
 30 ## Output: 10
 31 ##
 32 ## Pair 1: (1, -2)
 33 ## Pair 2: (3, -4)
 34 #
 35 #
 36 ## Example 3
 37 ##
 38 ## Input: @ints = (-3, -1, -2, -4)
 39 ## Output: 10
 40 ##
 41 ## Pair 1: (-1, -2)
 42 ## Pair 2: (-3, -4)
 43 #
 44 #
 45 ## Example 4
 46 ##
 47 ## Input: @ints = (10, 2, 0, 5, 1)
 48 ## Output: 50
 49 ##
 50 ## Pair 1: (10, 5)
 51 ## Pair 2: (0, 1)
 52 #
 53 #
 54 ## Example 5
 55 ##
 56 ## Input: @ints = (7, 8, 9, 10, 10)
 57 ## Output: 44
 58 ##
 59 ## Pair 1: (10, 10)
 60 ## Pair 2: (7, 8)
 61 #
 62 ############################################################
 63 ##
 64 ## discussion
 65 ##
 66 ############################################################
 67 #
 68 # We pick all possible combinations of 4 numbers of the input. Then we
 69 # create all possible diffs for those 4 numbers which due to the symmetry
 70 # of the diff calculation and the possibility to use the absolute value of
 71 # the diff comes down to 3 different possibilities for any set of 4 numbers.
 72 # So we pick the max of those 3 numbers and the current max to find the
 73 # final result in the end.
 74 
 75 use v5.36;
 76 use List::Util qw(max);
 77 
 78 max_diff(5, 9, 3, 4, 6);
 79 max_diff(1, -2, 3, -4);
 80 max_diff(-3, -1, -2, -4);
 81 max_diff(10, 2, 0, 5, 1);
 82 max_diff(7, 8, 9, 10, 10);
 83 
 84 sub max_diff(@ints) {
 85     say "Input: (" . join(", ", @ints) . ")";
 86     my $output = 0;
 87     foreach my $i (0..$#ints) {
 88         foreach my $j ($i+1..$#ints) {
 89             foreach my $k ($j+1..$#ints) {
 90                 foreach my $l ($k+1..$#ints) {
 91                     $output = max($output,
 92                         abs($ints[$i]*$ints[$j] - $ints[$k]*$ints[$l]),
 93                         abs($ints[$i]*$ints[$k] - $ints[$j]*$ints[$l]),
 94                         abs($ints[$i]*$ints[$l] - $ints[$k]*$ints[$j])
 95                     );
 96                 }
 97             }
 98         }
 99     }
100 
101     say "Output: $output";
102 }