Maximum Count of Positive Integer and Negative Integer - 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.

Note: 0 is neither positive nor negative.

Input & Output

Example 1 — More Negatives
$ Input: nums = [-2,-1,-1,1,2,3]
Output: 3
💡 Note: There are 3 negative integers and 3 positive integers. Return max(3, 3) = 3.
Example 2 — More Positives
$ Input: nums = [-3,-2,-1,0,0,1,2]
Output: 3
💡 Note: There are 3 negative integers and 2 positive integers. Return max(3, 2) = 3.
Example 3 — Only Positives
$ Input: nums = [5,20,66,1314]
Output: 4
💡 Note: There are 0 negative integers and 4 positive integers. Return max(0, 4) = 4.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • -2000 ≤ nums[i] ≤ 2000
  • nums is sorted in non-decreasing order

Visualization

Tap to expand
Maximum Count of Positive and Negative NumbersInput: [-3,-2,-1,0,0,1,2] (sorted array)-3-2-10012Negatives: 3Zeros: 2 (ignored)Positives: 2Compare counts: max(3 negatives, 2 positives)Output: 3
Understanding the Visualization
1
Input Array
Sorted array with negative, zero, and positive numbers
2
Count Each Type
Count negatives and positives (ignore zeros)
3
Return Maximum
Return the larger of the two counts
Key Takeaway
🎯 Key Insight: Use the sorted property to find boundaries efficiently with binary search instead of counting every element
Asked in
Microsoft 15 Amazon 12 Apple 8
35.0K Views
Medium Frequency
~10 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