Peter’s blog ✴ Week 338 ✴ 8 September 2025
THE WEEKLY CHALLENGE
High and far
You are given two integer arrays, @arr1 and @arr2.
Write a script to find the maximum difference between any pair of values from both arrays.
Example 1 Input: @arr1 = (4, 5, 7) @arr2 = (9, 1, 3, 4) Output: 6 With element $arr1[0] = 4 | 4 - 9 | = 5 | 4 - 1 | = 3 | 4 - 3 | = 1 | 4 - 4 | = 0 max distance = 5 With element $arr1[1] = 5 | 5 - 9 | = 4 | 5 - 1 | = 4 | 5 - 3 | = 2 | 5 - 4 | = 1 max distance = 4 With element $arr1[2] = 7 | 7 - 9 | = 2 | 7 - 1 | = 6 | 7 - 3 | = 4 | 7 - 4 | = 4 max distance = 6 max (5, 6, 6) = 6 Example 2 Input: @arr1 = (2, 3, 5, 4) @arr2 = (3, 2, 5, 5, 8, 7) Output: 6 Example 3 Input: @arr1 = (2, 1, 11, 3) @arr2 = (2, 5, 10, 2) Output: 9 Example 4 Input: @arr1 = (1, 2, 3) @arr2 = (3, 2, 1) Output: 2 Example 5 Input: @arr1 = (1, 0, 2, 3) @arr2 = (5, 0) Output: 5
Well, here's the easy way: sort both arrays, and the answer is the larger of the absolute differences between:
Granted, sorting is probably more expensive than doing two nested loops, but I tried my solution with a million elements in each array and it only took 2.5 seconds.
Peter's solutions are exemplary models of clarity, robustness and efficiency. He deliberately chooses transparent, verbose code over clever one-liners, making his solutions easy to understand and maintain. Furthermore, he demonstrates deep insight by identifying and implementing highly efficient algorithms, especially for the second task.
This review may cover either or both challenges for this week.
I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-09-08 use utf8; # Week 338 - task 2 - Max distance use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; max_distance([4, 5, 7], [9, 1, 3, 4]); max_distance([2, 3, 5, 4], [3, 2, 5, 5, 8, 7]); max_distance([2, 1, 11, 3], [2, 5, 10, 2]); max_distance([1, 2, 3], [3, 2, 1]); max_distance([1, 0, 2, 3], [5, 0]); sub max_distance { my (@one, @two, $diff1, $diff2); # initialise @one = sort {$a <=> $b} @{$_[0]}; @two = sort {$a <=> $b} @{$_[1]}; $diff1 = abs($one[0] - $two[-1]); $diff2 = abs($one[-1] - $two[0]); say qq{\nInput: [} . join(', ', @{$_[0]}) . '], [' . join(', ', @{$_[1]}) . ']'; say qq[Output: ] . ($diff1 > $diff2 ? $diff1 : $diff2); }
8 lines of code
Input: [4, 5, 7], [1, 3, 4, 9] Output: 6 Input: [2, 3, 4, 5], [2, 3, 5, 5, 7, 8] Output: 6 Input: [1, 2, 3, 11], [2, 2, 5, 10] Output: 9 Input: [1, 2, 3], [1, 2, 3] Output: 2 Input: [0, 1, 2, 3], [0, 5] Output: 5
Any content of this website which has been created by Peter Campbell Smith is in the public domain