Leetcode 2529. Maximum Count of Positive Integer and Negative Integer
The problem is about counting the number of positive and negative integers in a given array and returning the maximum count between these two counts.
You are given an array nums
that may contain positive integers, negative integers, and zeros. You need to return the maximum of the counts of positive integers and negative integers in the array.
Can the array contain zero? Yes, the array can contain zero, but zero is neither positive nor negative, so it should not be counted in either category.
What is the range of numbers in the array? The problem does not specify the exact range, but typically it could be any 32-bit integer.
Are there any constraints on the length of the array? The problem statement does not specify constraints, but typically LeetCode problems assume the array can have up to (10^5) elements.
To solve this problem, we can simply iterate through the array and maintain two counters:
After traversing the array, we compare these two counters and return the maximum value.
Here’s the C++ implementation of the solution:
#include <vector>
#include <algorithm>
class Solution {
public:
int maximumCount(std::vector<int>& nums) {
int positiveCount = 0;
int negativeCount = 0;
for (int num : nums) {
if (num > 0) {
++positiveCount;
} else if (num < 0) {
++negativeCount;
}
}
return std::max(positiveCount, negativeCount);
}
};
// Example usage:
// int main() {
// Solution solution;
// std::vector<int> nums = {-1, -2, -3, 0, 1, 2, 3};
// int result = solution.maximumCount(nums);
// std::cout << "Maximum count of positive or negative integers: " << result << std::endl;
// return 0;
// }
The time complexity of this solution is (O(n)), where (n) is the number of elements in the array nums
. This is because we only need to iterate through the array once to count the positives and negatives.
The space complexity is (O(1)) since we are using a constant amount of extra space (only a few integer variables for counting).
This approach ensures that the problem is solved efficiently and correctly.
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?