Maximum Count of Positive Integer and Negative Integer — LeetCode 2529 Python Solution
- Problem
- #2529
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(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.