LeetCode: Maximum Distance Between A Pair Of Values Solution

1/**
2 * @param {number[]} nums1
3 * @param {number[]} nums2
4 * @return {number}
5 */
6// binary search, O(nlogn)
7var maxDistance = function (nums1, nums2) {
8 let max = 0
9
10 for (let i = 0; i < nums1.length; i++) {
11 let left = i
12 let right = nums2.length - 1
13 let mid
14 while (left <= right) {
15 mid = Math.floor((left + right) / 2)
16 if (nums1[i] > nums2[mid]) {
17 right = mid - 1
18 } else {
19 max = Math.max(max, Math.max(0, mid - i))
20 left = mid + 1
21 }
22 }
23 }
24
25 return max
26}
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 max
42}

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.

Next Post

LeetCode: Maximum Population Year

HoningJS

Search Posts