algoadvance

Leetcode 2529. Maximum Count of Positive Integer and Negative Integer

Problem Statement

You are given an array containing both positive and negative integers. Your task is to find the maximum count of either strictly positive or strictly negative integers.

In other words, you should return the count of the majority of the integers in the array. If the counts of positive and negative integers are the same, return that count.

Clarifying Questions

  1. Q: What should the function return if the input array is empty?
    • A: If the input array is empty, there are no positive or negative numbers, so the function should return 0.
  2. Q: What should the function return if there are only zeros in the array?
    • A: Zeros are neither positive nor negative. If the array comprises only zeros, the function should return 0.
  3. Q: Is the input array sorted?
    • A: The problem does not specify that the array is sorted, so we should assume it can be in any order.
  4. Q: What is the expected time complexity?
    • A: The problem does not specify constraints, but we should aim for an efficient solution, ideally O(n), where n is the length of the input array.

Strategy

  1. Initialize two counters: one for counting positive integers (positiveCount) and one for counting negative integers (negativeCount).
  2. Iterate through each element of the array:
    • If the element is positive, increment positiveCount.
    • If the element is negative, increment negativeCount.
  3. Compare the two counters and return the maximum of the two.

Time Complexity

Code

public class Solution {
    public int maximumCount(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);
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums1 = {1, -2, 3, -4, 5, -6}; // Expected output: 3 (there are 3 positive integers and 3 negative integers)
        int[] nums2 = {-1, -2, -3, -4, -5}; // Expected output: 5 (there are 5 negative integers)
        int[] nums3 = {1, 2, 3, 4, 5}; // Expected output: 5 (there are 5 positive integers)
        int[] nums4 = {0, 0, 0}; // Expected output: 0 (there are no positive or negative integers)

        System.out.println(sol.maximumCount(nums1)); // 3
        System.out.println(sol.maximumCount(nums2)); // 5
        System.out.println(sol.maximumCount(nums3)); // 5
        System.out.println(sol.maximumCount(nums4)); // 0
    }
}

By following this approach, we ensure that the solution is both efficient and easy to understand.

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