#2529
Maximum Count of Positive Integer and Negative Integer
EasyArrayBinary SearchCountingBinary SearchArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
Since the array is sorted, we can use binary search to find the point where positive integers start. This allows us to count positives and negatives efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Use binary search to find the index of the first positive integer.
- 2Step 2: The count of positive integers is the length of the array minus this index.
- 3Step 3: The count of negative integers is simply this index.
- 4Step 4: Return the maximum of the counts from steps 2 and 3.
solution.py13 lines
1# Full working Python code
2
3def maxCount(nums):
4 left, right = 0, len(nums) - 1
5 while left <= right:
6 mid = (left + right) // 2
7 if nums[mid] < 0:
8 left = mid + 1
9 else:
10 right = mid - 1
11 neg_count = left
12 pos_count = len(nums) - neg_count
13 return max(pos_count, neg_count)ℹ
Complexity note: This complexity is due to the binary search, which efficiently narrows down the search space logarithmically.
- 1The array is sorted, allowing for efficient counting using binary search.
- 2Zero does not affect the count of positive or negative integers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.