Techieindoor

Leetcode 2529: Maximum Count of Positive Integer and Negative Integer Solution

Here, we will see how to solve Maximum Count of Positive Integer and Negative Integer solution of leet code 2529 problem.

You are given an array nums sorted in non-decreasing order, return the maximum between the number of positive integers and the number of negative integers.

In other words, if the number of positive integers in nums is pos and the number of negative integers is neg, then return the maximum of pos and neg.

Note: here, digit 0 will not be counted in positive integer.

Example 1:

Input: nums = [-2,-1,-1,1,2,3,4]
Output: 4
Explanation: There are 4 positive integers and 3 negative integers. The maximum count among them is 4.

Example 2:

Input: nums = [-3,-2,-1,0,0,1,2]
Output: 3
Explanation: There are 2 positive integers and 3 negative integers. The maximum count among them is 3. Here, O(zero) will not be counted as positive integer.

Example 3:

Input: nums = [15,22,66,1314]
Output: 4
Explanation: There are 4 positive integers and 0 negative integers. The maximum count among them is 4.

Approach:

Maximum Count of Positive Integer and Negative Integer Solution in C++ and Go:

Here, we will be solving problem in multiple ways with code.

C++ code 1:

class Solution {
public:
    int maximumCount(vector<int>& nums) {
        int neg = 0, pos = 0;
        
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] < 0) {
                neg++;
            } else if(nums[i] > 0){
                pos++;
            }
        }
        return pos > neg ? pos: neg;
    }
};

Go code 1:

func maximumCount(nums []int) int {
    var pos, neg = 0, 0

    for i := 0; i < len(nums); i++ {
        if nums[i] < 0 {
            neg++
        } else if nums[i] > 0 {
            pos++
        }
    }
    if pos > neg {
            return pos
    } else {
        return neg
    }
}

Output:

Input: nums = [-2,-1,-1,1,2,3,4]
Output: 4

Time complexity: O(n)

Space complexity: O(1)

To check more leetcode problem’s solution. Pls click given below link:

Golang tutorial

https://www.techieindoor.com/category/leetcode/

https://www.techieindoor.com/category/interview-questions/

Exit mobile version