Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Created April 20, 2016 14:14
Show Gist options
  • Save sword-jin/82539226913b9910122619966201f153 to your computer and use it in GitHub Desktop.
Save sword-jin/82539226913b9910122619966201f153 to your computer and use it in GitHub Desktop.
x1,y1,x2,y2....最大距离

You are given a set of points on the Cartesian plane. Consider the distance between two points as the maximum difference of their coordinates. For example, the distance between points (1, 2) and (4, 6) is equal to max(|4 - 1|, |6 - 2|) = 4.

Given a set of points, find the pair with the largest distance and return the value of their distance.

Example

For A = [7, 6, 6, 8, 1, 2, 8, 6], the output should be
largestDistance(A) = 7.

[input] array.integer A

Points are given in one array A, where A[2 * i] is the x coordinate of the ith point, and A[2 * i + 1] is the y coordinate of the ith point. All coordinates are positive. The number of points is less than 1000. The points are not necessarily distinct.

[output] integer

The maximum distance between two points from the input set.
function largestDistance(A) {
var mx = [A[0], A[1]];
var mn = [A[1], A[0]];
for (var i = 0; i < A.length; i++) {
var k = i % 2;
if (A[i] > mx[k]) {
mx[k] = A[i];
} else if (A[i] < mn[k]) {
mn[k] = A[i];
}
}
return Math.max(mx[0] - mn[0], mx[1] - mn[1]);
}
@khushi4tiwari
Copy link

It should go up to A.length-1 because for test cases like [1,2,2,0] it will fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment