Given an integer array nums
, return the maximum count of either positive integers or negative integers.
We will traverse the array once, maintaining two counters: one for counting positive integers and another for negative integers. At the end of the traversal, we return the maximum of these two counts.
The time complexity for this approach is (O(n)), where (n) is the size of the input array nums
. This is because we only need to traverse the array once.
def maximumCount(nums):
positive_count = 0
negative_count = 0
for num in nums:
if num > 0:
positive_count += 1
elif num < 0:
negative_count += 1
return max(positive_count, negative_count)
# Example usage:
nums = [1, -2, -3, 4, -5, 0]
print(maximumCount(nums)) # Output should be 3
The example provided within the code includes zeros to demonstrate that they are indeed ignored in the count. The maximum count of either positive or negative integers is 3
in this example (i.e., there are 3 negative numbers).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?