algoadvance

Leetcode 2529. Maximum Count of Positive Integer and Negative Integer

Problem Statement

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.

Clarifying Questions

  1. 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.

  2. 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.

  3. 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.

Strategy

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.

Code

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;
// }

Time Complexity

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.

Space Complexity

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.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI