Task 1: Max Positive Negative
You are given an array of integers, @ints.
Write a script to return the maximum number of either positive or negative integers in the given array.
Example 1: Input: @ints = (-3, 1, 2, -1, 3, -2, 4) → Output: 4 (4 positive, 3 negative)
Example 2: Input: @ints = (-1, -2, -3, 1) → Output: 3
Example 3: Input: @ints = (1, 2) → Output: 2
Method Explanation
To determine the larger count between strictly positive (> 0) and strictly negative (< 0) elements in @ints (remembering that 0 is neither positive nor negative):
- Count the number of elements strictly greater than zero.
- Count the number of elements strictly less than zero.
- Return the maximum of the two counts.
Scanning the array takes $O(N)$ time and $O(1)$ auxiliary space.
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
signature_for max_positive_negative => (
method => 0,
positional => [ ArrayRef [Int] ],
);
sub max_positive_negative ($ints) {
my $positive_count = scalar( grep { $_ > 0 } @$ints );
my $negative_count = scalar( grep { $_ < 0 } @$ints );
return $positive_count > $negative_count ? $positive_count : $negative_count;
}
Python Solution
def max_positive_negative(ints: list[int]) -> int:
"""Return the maximum count of either positive or negative integers."""
positive_count = sum(1 for x in ints if x > 0)
negative_count = sum(1 for x in ints if x < 0)
return max(positive_count, negative_count)