Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]
Solution: Binary Search
Since nums is sorted, we can use binary search:
- Binary search for the index of the rightmost negative number.
- Binary search for the index of the leftmost positive number.
Based on the indexes we can find the amount of negative and positive numbers.
Time Complexity: O(log(n)) 64ms
Space Complexity: O(1) 43.7MB
var maximumCount = function(nums) {
return Math.max(upper_bound(nums), lower_bound(nums));
};
// binary search for the rightmost negative number
function upper_bound(nums) {
let low = 0, high = nums.length - 1;
while (low < high) {
let mid = Math.ceil((low + high) / 2);
if (nums[mid] < 0) low = mid;
else high = mid - 1;
}
return nums[0] >= 0 ? 0 : low + 1;
}
// binary search for the leftmost positive number
function lower_bound(nums) {
let low = 0, high = nums.length - 1;
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (nums[mid] > 0) high = mid;
else low = mid + 1;
}
return nums[nums.length - 1] <= 0 ? 0 : nums.length - low;
}
Comments
Post a Comment