Task 1: Max Diff
"Pair Products: Find the Widest Gap!"
Given an array of at least four integers, find two disjoint pairs whose product difference is as large as possible. Return the maximum absolute difference.
The Strategy: Enumerate all combinations of 4 indices. For each quadruple, try all three ways to split into two pairs, compute the product of each pair, and track the maximum absolute difference. A brute-force O(n^4) approach that works well for small inputs.
Perl Implementation
sub max_product_difference {
my (@ints) = @_;
die 'Need at least four integers' if @ints < 4;
my $max_diff = 0;
for my $i ( 0 .. $#ints - 3 ) {
for my $j ( $i + 1 .. $#ints - 2 ) {
for my $k ( $j + 1 .. $#ints - 1 ) {
for my $l ( $k + 1 .. $#ints ) {
my @vals = @ints[ $i, $j, $k, $l ];
my @pairings = (
[ [ $vals[0], $vals[1] ], [ $vals[2], $vals[3] ] ],
[ [ $vals[0], $vals[2] ], [ $vals[1], $vals[3] ] ],
[ [ $vals[0], $vals[3] ], [ $vals[1], $vals[2] ] ],
);
for my $pair (@pairings) {
my ( $first, $second ) = @$pair;
my $prod1 = $first->[0] * $first->[1];
my $prod2 = $second->[0] * $second->[1];
my $diff = abs( $prod1 - $prod2 );
$max_diff = $diff if $diff > $max_diff;
}
}
}
}
}
return $max_diff;
}
Python Implementation
def max_product_difference(ints: list[int]) -> int:
"""Maximum absolute difference of products from two disjoint pairs."""
from itertools import combinations
if len(ints) < 4:
raise ValueError("Need at least four integers")
best = 0
for quad in combinations(ints, 4):
a, b, c, d = quad
for (x, y), (w, z) in [
((a, b), (c, d)),
((a, c), (b, d)),
((a, d), (b, c)),
]:
diff = abs(x * y - w * z)
best = max(best, diff)
return best