int getMaxDistanceSquare(int A, int B, int C, int D)
Assume that:
A, B, C and D are integers within the range [-5000, 5000]
For example, let's consider the following values:
A = 1
B = 1
C = 2
D = 3
We have:
(1, 1) <=> (2, 3) or (3, 2) squared distance = 5 or 5 MAX = 5
(1, 2) <=> (1, 3) (3, 1) 1 5
(1, 3) <=> (1, 2) (2, 1) 1 5
For Example,
A = 2
B = 4
C = 2
D = 4
We have:
(2, 4) <=> (2, 4) or (4, 2) squared distance = 0 or 8 MAX = 8
(2, 2) <=> (4, 4) 8
(2, 4) <=> (4, 2) or (2, 4) 8 0
For Example,
A = 1
B = 2
C = 3
D = 4
We have:
(1, 2) <=> (3, 4) or (4, 3) squared distance = 8 or 10 MAX = 10
(1, 3) <=> (2, 4) or (4, 2) 1 10
(1, 4) <=> (2, 3) or (3, 2) 1 8
My Solution: (Might be wrong, please advice)
static int getMaxDistanceSquare(int A, int B, int C, int D){ int max = -1; int[] dist = new int[3]; dist[0] = (A-B)*(A-B) + (C-D)*(C-D); dist[1] = (A-C)*(A-C) + (B-D)*(B-D); dist[2] = (A-D)*(A-D) + (B-C)*(B-C); for(int i = 0; i < 2; i++) max = dist[i] > dist[i+1] ? dist[i] : dist[i+1]; return max; }
private int calcSquaredDistance(int A, int B, int C, int D) {
ReplyDelete// If all points are equal then return 0
if ((A==B) && (B==C) && (C==D)) {
return 0;
}
List list = new ArrayList<>();
list.add(A);
list.add(B);
list.add(C);
list.add(D);
Collections.sort(list);
int x1 = list.get(0);
int y1 = list.get(1);
int x2 = list.get(3);
int y2 = list.get(2);
return ((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1));
}