# LeetCode: Maximum Distance Between A Pair Of Values Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} nums13 * @param {number[]} nums24 * @return {number}5 */6// binary search, O(nlogn)7var maxDistance = function (nums1, nums2) {8  let max = 09
10  for (let i = 0; i < nums1.length; i++) {11    let left = i12    let right = nums2.length - 113    let mid14    while (left <= right) {15      mid = Math.floor((left + right) / 2)16      if (nums1[i] > nums2[mid]) {17        right = mid - 118      } else {19        max = Math.max(max, Math.max(0, mid - i))20        left = mid + 121      }22    }23  }24
25  return max26}27
28// two pointers, O(n)29var maxDistance = function (nums1, nums2) {30  let [i, j, max] = [0, 0, 0]31
32  while (i < nums1.length && j < nums2.length) {33    if (nums1[i] > nums2[j]) {34      i++35    } else {36      j++37    }38    max = Math.max(max, j - i - 1)39  }40
41  return max42}```

leetcode

two pointers

binary search

greedy

## Next Post

LeetCode: Maximum Population Year

May 9, 2021

Search Posts