Maximum Width Ramp - Montonic Decreasing Stack w/ Binary Search [JS]

Description 

Solution: Monotonic Decreasing Stack & Binary Search

Keep a monotonic decreasing stack, there is no point in keeping bigger or equal numbers that are at later indexes.
For each nums[i], use binary search for the leftmost index in the stack where nums[stack[index]] <= nums[i].
Only push the current number into the stack if it is smaller than the last number on the stack.

Time Complexity: O(n log(n)) 109ms
Space Complexity: O(n) 48.2MB

var maxWidthRamp = function(nums) {
  let stack = [], ans = 0;
  for (let i = 0; i < nums.length; i++) {
    let index = lower_bound(stack, i);
    ans = Math.max(ans, i - index);
    if (!stack.length || nums[i] < nums[stack[stack.length - 1]]) stack.push(i);
  }
  return ans;
  
  function lower_bound(arr, index) {
    if (!arr.length) return index;
    let low = 0, high = arr.length - 1;
    while (low < high) {
      let mid = Math.floor((low + high) / 2);
      if (nums[arr[mid]] <= nums[index]) high = mid;
      else low = mid + 1;
    }
    return nums[arr[low]] <= nums[index] ? arr[low] : index;
  }
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]

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

Count Subarrays With Median K - Count Left & Right Balance [JS]