Task 1: Distinct Average
"Balanced Removal: Counting Unique Mean Values!"
Given an even-length array, repeatedly remove the minimum and maximum values, calculate their average, and count how many unique averages were found.
The Strategy: First, sort the array in ascending order. Use two pointers: one at the start (min) and one at the end (max). In each step, calculate the average of the elements at these pointers, move the pointers toward each other, and store the average in a set (or hash) to automatically handle uniqueness.
Perl Implementation
sub distinct_average_count ($nums) {
my @sorted = sort { $a <=> $b } @$nums;
my %seen;
for ( my ( $l, $r ) = ( 0, $#sorted ); $l < $r; ++$l, --$r ) {
my $sum = $sorted[$l] + $sorted[$r];
$seen{ sprintf( '%.12g', $sum ) } = 1;
}
return scalar keys %seen;
}
Python Implementation
def distinct_average_count(nums: Sequence[Fraction]) -> int:
sorted_nums = sorted(nums)
seen: set[Fraction] = set()
left, right = 0, len(sorted_nums) - 1
while left < right:
seen.add((sorted_nums[left] + sorted_nums[right]) / 2)
left += 1
right -= 1
return len(seen)