Camel
Peter
Peter Campbell Smith

High and far

Weekly challenge 338 — 8 September 2025

Week 338: 8 Sep 2025

Task 2

Task — Max distance

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.

Examples


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

Analysis

Well, here's the easy way: sort both arrays, and the answer is the larger of the absolute differences between:

  • the first element of array 1 and the last of array 2, and
  • the first element of array 2 and the last of array 1.

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.

Try it 

Try running the script with any input:



example: [3, 1, 4], [1, 5, 9]

Script


#!/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);
}

Output


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