Maximum Count of Positive Integer and Negative Integer — LeetCode 2529 Python Solution

EasyArrayBinary SearchCounting
Problem
#2529
Reading time
2 min

The problem

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.

Example

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

Python solution

Python
class Solution:
    def maximumCount(self, nums: List[int]) -> int:
        a = sum(x > 0 for x in nums)
        b = sum(x < 0 for x in nums)
        return max(a, b)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2529. Maximum Count of Positive Integer and Negative Integer is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2529. Maximum Count of Positive Integer and Negative Integer?
LeetCode 2529. Maximum Count of Positive Integer and Negative Integer is rated Easy on LeetCode.
What is the time complexity of LeetCode 2529. Maximum Count of Positive Integer and Negative Integer?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2529. Maximum Count of Positive Integer and Negative Integer?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2529. Maximum Count of Positive Integer and Negative Integer cover?
LeetCode 2529. Maximum Count of Positive Integer and Negative Integer is tagged Array, Binary Search and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview