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: Positive vs Negative Integers INPUT Sorted Array (non-decreasing) 0 1 2 3 4 5 -2 -1 -1 1 2 3 Negative numbers Positive numbers Input Values nums = [-2,-1,-1,1,2,3] Length: 6 elements Sorted: Yes (non-decreasing) ALGORITHM STEPS 1 Binary Search for First Non-Negative Find index where nums[i] >= 0 2 Count Negatives neg = first non-neg index neg = 3 (indices 0,1,2) 3 Binary Search for First Positive (> 0) pos = n - first positive index pos = 6 - 3 = 3 4 Return Maximum return max(pos, neg) max(3, 3) = 3 Time: O(log n) | Space: O(1) Binary search on sorted array FINAL RESULT Count Comparison Negative Count 3 Positive Count 3 Both counts are equal! OUTPUT 3 OK max(3, 3) = 3 Key Insight: Since the array is sorted, all negatives are on the left and all positives on the right. Use binary search twice: once to find the boundary where numbers become non-negative, and once to find where they become positive. This gives O(log n) time complexity. TutorialsPoint - Maximum Count of Positive Integer and Negative Integer | Optimal Solution (Binary Search)
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