Skip to content

Commit 69ba683

Browse files
authored
Create 624-maximum-distance-in-arrays.js
1 parent 1d4afa4 commit 69ba683

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

624-maximum-distance-in-arrays.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
3+
Given m arrays, and each array is sorted in ascending order.
4+
Now you can pick up two integers from two different arrays (each array picks one)
5+
and calculate the distance.
6+
We define the distance between two integers a and b to be their absolute difference |a-b|.
7+
Your task is to find the maximum distance.
8+
9+
Example 1:
10+
11+
Input:
12+
[[1,2,3],
13+
[4,5],
14+
[1,2,3]]
15+
16+
Output: 4
17+
18+
Explanation:
19+
One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.
20+
21+
Note:
22+
Each given array will have at least 1 number. There will be at least two non-empty arrays.
23+
The total number of the integers in all the m arrays will be in the range of [2, 10000].
24+
The integers in the m arrays will be in the range of [-10000, 10000].
25+
26+
*/
27+
28+
/**
29+
* @param {number[][]} arrays
30+
* @return {number}
31+
*/
32+
const maxDistance = function(arrays) {
33+
if (arrays == null) return 0
34+
let result = 0
35+
let min = arrays[0][0]
36+
let max = arrays[0][arrays[0].length - 1]
37+
for (let i = 1; i < arrays.length; i++) {
38+
result = Math.max(
39+
result,
40+
Math.abs(arrays[i][arrays[i].length - 1] - min),
41+
Math.abs(arrays[i][0] - max)
42+
)
43+
max = Math.max(max, arrays[i][arrays[i].length - 1])
44+
min = Math.min(min, arrays[i][0])
45+
}
46+
return result
47+
}

0 commit comments

Comments
 (0)