Problem Description
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 the array. Note that 0 is neither positive nor negative.
Key Insights
- The array is already sorted, so binary search can be used to efficiently locate boundaries.
- Find the count of negative numbers by locating the first index where the number is no longer negative (i.e., >= 0).
- Find the count of positive numbers by locating the first index where the number is strictly positive (i.e., >= 1).
- Use the maximum of these counts as the final answer.
- Although a linear scan takes O(n) time, binary search reduces the time complexity to O(log n).
Space and Time Complexity
Time Complexity: O(log n) Space Complexity: O(1)
Solution
We perform two binary searches:
- The first binary search identifies the leftmost position of 0. The count of negatives is exactly the index of this position.
- The second binary search identifies the leftmost position of 1. The count of positives is the total length of the array minus this index. Return the maximum of these two counts. This approach leverages the sorted nature of the array for efficient boundary detection.