LeetCode 2529: Maximum Count of Positive Integer and Negative Integer

Problem Description

Explanation

To solve this problem, we can iterate through the sorted array and count the number of positive and negative integers separately. Then, we simply return the maximum count between the positive and negative integers. Since the array is already sorted, we can achieve this in linear time complexity.

  • Initialize variables positiveCount and negativeCount to 0.
  • Iterate through the sorted array nums:
    • If the current element is positive, increment positiveCount.
    • If the current element is negative, increment negativeCount.
  • Return the maximum of positiveCount and negativeCount.

Time Complexity

The time complexity of this solution is O(n), where n is the number of elements in the input array nums.

Space Complexity

The space complexity is O(1) since we are using only a constant amount of extra space.

Solutions

public int maxCount(int[] nums) {
    int positiveCount = 0;
    int negativeCount = 0;
    
    for (int num : nums) {
        if (num > 0) {
            positiveCount++;
        } else if (num < 0) {
            negativeCount++;
        }
    }
    
    return Math.max(positiveCount, negativeCount);
}

Loading editor...