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
Efficient Team Counting StrategySorted Jersey NumbersTeam A-3Team A-2Team A-1Referee0Referee0Team B1Team B2๐Ÿ” Binary SearchFind last Team A playerCount: 3๐Ÿ” Binary SearchFind first Team B playerCount: 2๐Ÿ† Winner: Team A with 3 players๐Ÿ’ก Smart StrategyInstead of counting each person (O(n)), use binary search to find boundaries (O(log n))
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

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using a few variables for binary search

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 2000
  • -2000 โ‰ค nums[i] โ‰ค 2000
  • nums is sorted in non-decreasing order
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen