The Weekly Challenge 320

Counting Integers & Digit Sum Differences!

Original Challenge Link

Task 1: Maximum Count

"Finding the Majority: Positives vs. Negatives!"

Given an array of integers, return the maximum between the count of positive integers and the count of negative integers. Zeros are ignored.

The Strategy: Iterate through the list once. Maintain two counters: one for positive numbers (val > 0) and one for negative numbers (val < 0). Return the larger of the two counts.
Perl Implementation
sub maximum_count ($ints) {
    my ($pos, $neg) = (0, 0);
    for my $n (@$ints) {
        ++$pos if $n > 0;
        ++$neg if $n < 0;
    }
    return $pos > $neg ? $pos : $neg;
}
Python Implementation
def maximum_count(ints: Sequence[int]) -> int:
    positives = sum(1 for value in ints if value > 0)
    negatives = sum(1 for value in ints if value < 0)
    return max(positives, negatives)

Task 2: Sum Difference

"Magnitude vs. Components: Calculating the Gap!"

Compute the absolute difference between the total sum of an array and the sum of all individual digits across its elements.

The Strategy: Calculate the element sum by summing the entire array. Calculate the digit sum by converting each number to its string representation, iterating over the individual digits (characters), and summing their integer values. Return the absolute difference between these two totals.
Perl Implementation
sub sum_difference ($ints) {
    my $element_sum = sum0(@$ints);
    my $digit_sum   = 0;
    for my $n (@$ints) {
        $digit_sum += sum0( split //, $n );
    }
    my $diff = $element_sum - $digit_sum;
    return $diff < 0 ? -$diff : $diff;
}
Python Implementation
def sum_difference(ints: Sequence[int]) -> int:
    element_sum = sum(ints)
    digit_sum = sum(int(digit) for value in ints for digit in str(value))
    return abs(element_sum - digit_sum)