Maximum Count of Positive Integer and Negative Integer - Problem
Given a sorted array nums in non-decreasing order, find the maximum between the count of positive integers and the count of negative integers.
Your task is to return max(positive_count, negative_count) where:
- Positive integers: numbers greater than 0
- Negative integers: numbers less than 0
- Zero: is neither positive nor negative (ignore it)
Example: In array [-3, -2, -1, 0, 0, 1, 2], we have 3 negative numbers and 2 positive numbers, so we return max(3, 2) = 3.
Since the array is already sorted, we can use this property to our advantage for an efficient solution!
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [-2, -1, -1, 1, 2, 3]
โบ
Output:
3
๐ก Note:
There are 3 negative integers and 3 positive integers. max(3, 3) = 3.
example_2.py โ With Zeros
$
Input:
nums = [-3, -2, -1, 0, 0, 1, 2]
โบ
Output:
3
๐ก Note:
There are 3 negative integers and 2 positive integers. Zeros don't count. max(3, 2) = 3.
example_3.py โ Only Positives
$
Input:
nums = [5, 20, 66, 1314]
โบ
Output:
4
๐ก Note:
There are 0 negative integers and 4 positive integers. max(0, 4) = 4.
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
In a sorted array: [negatives] [zeros] [positives]
2
Find Boundaries
Use binary search to find where negatives end and positives begin
3
Calculate Counts
Count = boundary_index calculations, no need to scan all elements
Key Takeaway
๐ฏ Key Insight: In a sorted array, we can use binary search to find boundaries between negative and positive numbers, allowing us to calculate counts in O(log n) time instead of scanning all elements in O(n) time.
Time & Space Complexity
Time Complexity
O(log n)
Two binary searches, each taking O(log n) time
โก Linearithmic
Space Complexity
O(1)
Only using a few variables for binary search
โ Linear Space
Constraints
- 1 โค nums.length โค 2000
- -2000 โค nums[i] โค 2000
- nums is sorted in non-decreasing order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code