LeetCode: Maximum Distance Between A Pair Of Values Solution
1/**2 * @param {number[]} nums13 * @param {number[]} nums24 * @return {number}5 */6// binary search, O(nlogn)7var maxDistance = function (nums1, nums2) {8 let max = 0910 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 }2425 return max26}2728// two pointers, O(n)29var maxDistance = function (nums1, nums2) {30 let [i, j, max] = [0, 0, 0]3132 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 }4041 return max42}
Comments
Loading comments...
Tags
leetcode
two pointers
binary search
greedy
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.