We need to calculate the count of positive and negative integers in a sorted array (nums) and return the maximum between the two. It is essential to note that nums is sorted in non-decreasing order, which allows us to use binary search or simple traversal for efficiency.
Identify Negatives: Using the sorted property of the array, the negative numbers will always appear at the start, followed by zero (if present), and then the positive numbers.
Binary Search for Transition Points:
To count negative numbers (neg), find the index of the first non-negative number (≥ 0).
For positive numbers (pos), find the index of the first positive number (> 0).
Calculate Counts: Subtract indices or use list slicing to count negative and positive numbers.
Return Result: Compute the maximum of neg and pos.
classSolution {
publicintmaximumCount(int[] nums) {
int n = nums.length;
int negCount = 0, posCount = 0;
// Find the first non-negative index (all before are negatives)int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid]< 0) {
negCount = mid + 1;
left = mid + 1;
} else {
right = mid - 1;
}
}
// Find the first positive index (all after are positives) left = 0; right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid]> 0) {
posCount = n - mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
// Return the maximum of negative and positive countsreturn Math.max(negCount, posCount);
}
}
classSolution:
defmaximumCount(self, nums: List[int]) -> int:
n: int = len(nums)
neg_count: int =0 pos_count: int =0# Find the first non-negative index left: int =0 right: int = n -1while left <= right:
mid: int = left + (right - left) //2if nums[mid] <0:
neg_count = mid +1 left = mid +1else:
right = mid -1# Find the first positive index left =0 right = n -1while left <= right:
mid: int = left + (right - left) //2if nums[mid] >0:
pos_count = n - mid
right = mid -1else:
left = mid +1# Return the maximum of negative and positive countsreturn max(neg_count, pos_count)