Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Description 

Solution: Binary Search

Since nums is sorted, we can use binary search:

  1. Binary search for the index of the rightmost negative number.
  2. 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

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]