2529. Maximum Count of Positive Integer and Negative Integer #1422
-
Topics: Given an array
Note that Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the maximum count between positive and negative integers in a given sorted array. The array is sorted in non-decreasing order, which allows us to efficiently find the counts using binary search. Approach
Let's implement this solution in PHP: 2529. Maximum Count of Positive Integer and Negative Integer <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maximumCount($nums) {
$n = count($nums);
$first_non_negative = findFirstNonNegative($nums);
$first_positive = findFirstPositive($nums);
$neg = $first_non_negative;
$pos = $n - $first_positive;
return max($neg, $pos);
}
/**
* @param $nums
* @return int
*/
function findFirstNonNegative($nums) {
$low = 0;
$high = count($nums) - 1;
$result = count($nums);
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($nums[$mid] >= 0) {
$result = $mid;
$high = $mid - 1;
} else {
$low = $mid + 1;
}
}
return $result;
}
/**
* @param $nums
* @return int
*/
function findFirstPositive($nums) {
$low = 0;
$high = count($nums) - 1;
$result = count($nums);
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($nums[$mid] > 0) {
$result = $mid;
$high = $mid - 1;
} else {
$low = $mid + 1;
}
}
return $result;
}
// Test cases
$test1 = [-2,-1,-1,1,2,3];
$test2 = [-3,-2,-1,0,0,1,2];
$test3 = [5,20,66,1314];
echo maximumCount($test1) . "\n"; // Output: 3
echo maximumCount($test2) . "\n"; // Output: 3
echo maximumCount($test3) . "\n"; // Output: 4
?> Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to determine the maximum count between positive and negative integers in a given sorted array. The array is sorted in non-decreasing order, which allows us to efficiently find the counts using binary search.
Approach