2529. Maximum Count of Positive Integer and Negative Integer
Problem Description
You are given an array nums
that is sorted in non-decreasing order (smallest to largest). Your task is to count how many positive integers and how many negative integers are in the array, then return whichever count is larger.
Key points to understand:
- The array is already sorted from smallest to largest
- You need to count positive integers (numbers greater than 0)
- You need to count negative integers (numbers less than 0)
- The number 0 is neither positive nor negative, so don't count it
- Return the maximum between these two counts
For example, if an array has 3 negative numbers and 5 positive numbers, you would return 5 since that's the larger count.
The solution approach is straightforward - traverse through the array once, counting elements that are greater than 0 for positive integers and elements that are less than 0 for negative integers. Then return the maximum of these two counts using max(a, b)
.
Intuition
Since we need to find the maximum between the count of positive and negative integers, the most direct approach is to simply count both types of numbers and compare them.
The key insight is that we don't need to do anything complex - we just need two counters. We can traverse the array once and for each element, determine if it's positive (x > 0
) or negative (x < 0
). Zero values are automatically ignored since they don't satisfy either condition.
Python's built-in sum()
function combined with generator expressions makes this particularly elegant. The expression sum(x > 0 for x in nums)
counts how many elements satisfy the condition x > 0
by creating a series of True/False values (which Python treats as 1/0) and summing them up. This gives us the count of positive numbers. Similarly, sum(x < 0 for x in nums)
counts negative numbers.
While the array being sorted might suggest we could use binary search to find the boundaries between negative, zero, and positive regions more efficiently, for most practical cases, a simple linear scan is sufficient and the code remains much cleaner and easier to understand. The time complexity is still O(n)
which is optimal since we need to count elements anyway.
Learn more about Binary Search patterns.
Solution Approach
The solution uses a simple traversal approach to count positive and negative integers separately, then returns the maximum of the two counts.
Implementation Steps:
-
Count positive integers: We use
sum(x > 0 for x in nums)
to count all positive numbers. This generator expression iterates through each elementx
innums
, evaluates the conditionx > 0
(which returnsTrue
orFalse
), andsum()
adds up these boolean values (treatingTrue
as 1 andFalse
as 0). The result is stored in variablea
. -
Count negative integers: Similarly, we use
sum(x < 0 for x in nums)
to count all negative numbers. The conditionx < 0
identifies negative integers, and the sum gives us the total count, stored in variableb
. -
Return the maximum: We use
max(a, b)
to return the larger of the two counts.
Why this works:
- The conditions
x > 0
andx < 0
naturally exclude zeros, since 0 is neither positive nor negative - Each element is checked exactly once, making this an
O(n)
time complexity solution - The space complexity is
O(1)
as we only use two variables to store the counts
Example walkthrough:
If nums = [-3, -2, -1, 0, 0, 1, 2]
:
- Positive count:
sum(x > 0 for x in nums)
evaluates to 2 (for elements 1 and 2) - Negative count:
sum(x < 0 for x in nums)
evaluates to 3 (for elements -3, -2, -1) - Return
max(2, 3) = 3
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with the array nums = [-4, -1, 0, 3, 5, 6]
:
Step 1: Count positive integers
- We iterate through each element and check if it's greater than 0
-4 > 0
? False (0)-1 > 0
? False (0)0 > 0
? False (0)3 > 0
? True (1)5 > 0
? True (1)6 > 0
? True (1)- Sum: 0 + 0 + 0 + 1 + 1 + 1 = 3 positive integers
Step 2: Count negative integers
- We iterate through each element and check if it's less than 0
-4 < 0
? True (1)-1 < 0
? True (1)0 < 0
? False (0)3 < 0
? False (0)5 < 0
? False (0)6 < 0
? False (0)- Sum: 1 + 1 + 0 + 0 + 0 + 0 = 2 negative integers
Step 3: Return the maximum
- We have 3 positive integers and 2 negative integers
max(3, 2) = 3
- Return 3
Notice how the zero in the array is automatically excluded from both counts since it's neither positive nor negative. The solution correctly identifies and counts only the relevant integers, then returns the larger count.
Solution Implementation
1class Solution:
2 def maximumCount(self, nums: List[int]) -> int:
3 """
4 Find the maximum count between positive and negative integers in the array.
5
6 Args:
7 nums: A list of integers (sorted in non-decreasing order)
8
9 Returns:
10 The maximum count between positive and negative integers
11 """
12 # Count the number of positive integers in the array
13 positive_count = sum(1 for num in nums if num > 0)
14
15 # Count the number of negative integers in the array
16 negative_count = sum(1 for num in nums if num < 0)
17
18 # Return the maximum between positive and negative counts
19 return max(positive_count, negative_count)
20
1class Solution {
2 /**
3 * Finds the maximum count between positive and negative numbers in an array.
4 *
5 * @param nums the input array of integers
6 * @return the maximum count between positive and negative numbers
7 */
8 public int maximumCount(int[] nums) {
9 // Counter for positive numbers
10 int positiveCount = 0;
11
12 // Counter for negative numbers
13 int negativeCount = 0;
14
15 // Iterate through each number in the array
16 for (int number : nums) {
17 // Check if the number is positive
18 if (number > 0) {
19 positiveCount++;
20 }
21 // Check if the number is negative
22 else if (number < 0) {
23 negativeCount++;
24 }
25 // Zero values are ignored (neither positive nor negative)
26 }
27
28 // Return the maximum count between positive and negative numbers
29 return Math.max(positiveCount, negativeCount);
30 }
31}
32
1class Solution {
2public:
3 int maximumCount(vector<int>& nums) {
4 // Count positive and negative numbers
5 int positiveCount = 0;
6 int negativeCount = 0;
7
8 // Iterate through all numbers in the array
9 for (int num : nums) {
10 if (num > 0) {
11 // Increment positive counter for positive numbers
12 ++positiveCount;
13 } else if (num < 0) {
14 // Increment negative counter for negative numbers
15 ++negativeCount;
16 }
17 // Skip zeros (neither positive nor negative)
18 }
19
20 // Return the maximum count between positive and negative numbers
21 return max(positiveCount, negativeCount);
22 }
23};
24
1/**
2 * Finds the maximum count between positive and negative numbers in an array
3 * @param nums - Array of integers to analyze
4 * @returns The maximum count between positive numbers and negative numbers
5 */
6function maximumCount(nums: number[]): number {
7 // Initialize counters for positive and negative numbers
8 let positiveCount: number = 0;
9 let negativeCount: number = 0;
10
11 // Iterate through each number in the array
12 for (const num of nums) {
13 if (num > 0) {
14 // Increment positive counter for positive numbers
15 positiveCount++;
16 } else if (num < 0) {
17 // Increment negative counter for negative numbers
18 negativeCount++;
19 }
20 // Zero values are ignored (neither positive nor negative)
21 }
22
23 // Return the maximum count between positive and negative numbers
24 return Math.max(positiveCount, negativeCount);
25}
26
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the array nums
. This is because the code iterates through the entire array twice - once to count positive numbers using sum(x > 0 for x in nums)
and once to count negative numbers using sum(x < 0 for x in nums)
. Each iteration takes O(n)
time, and O(n) + O(n) = O(n)
.
The space complexity is O(1)
. The algorithm only uses two additional variables a
and b
to store the counts of positive and negative numbers respectively, which requires constant extra space regardless of the input size. The generator expressions used in the sum()
functions don't create intermediate lists but instead process elements one at a time, maintaining constant space usage.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
Pitfall 1: Inefficient O(n) traversal for sorted arrays
The Problem: While the current solution correctly counts positive and negative integers with O(n) time complexity, it doesn't leverage the fact that the array is already sorted. In a sorted array, we can find the boundaries between negative, zero, and positive numbers using binary search, achieving O(log n) time complexity instead.
Why it matters: For large arrays, the difference between O(n) and O(log n) can be significant. If you have an array with millions of elements, binary search would be exponentially faster.
The Solution: Use binary search to find:
- The index of the first non-negative number (end of negative numbers)
- The index of the first positive number (start of positive numbers)
class Solution:
def maximumCount(self, nums: List[int]) -> int:
# Binary search for the first non-negative number (>= 0)
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] < 0:
left = mid + 1
else:
right = mid
negative_count = left
# Binary search for the first positive number (> 0)
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] <= 0:
left = mid + 1
else:
right = mid
positive_count = len(nums) - left
return max(negative_count, positive_count)
Pitfall 2: Counting zeros accidentally
The Problem: Using incorrect comparison operators like >=
or <=
instead of >
and <
would incorrectly include zeros in the count.
Example of incorrect code:
# WRONG - this would count zeros as positive
positive_count = sum(1 for num in nums if num >= 0)
The Solution: Always use strict inequalities (>
for positive, <
for negative) to exclude zeros from both counts.
How does quick sort divide the problem into subproblems?
Recommended Readings
Binary Search Speedrun For each of the Speedrun questions you will be given a binary search related problem and a corresponding multiple choice question The multiple choice questions are related to the techniques and template s introduced in the binary search section It's recommended that you have gone through at
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!