Keko has N dots in a 2-D coordinate plane. He wants to measure the gap between the most distant two dots. To make the problem easier, Keko decided to change each dot's x or y coordinate to zero.
Help Keko calculate the distance!
Example:
Input: n = 4, coordinates = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}
Output: 2.0000000000
Approach
Java
public class MostDistant {public static void main(String[] args) {int n = 4;double[][] coordinates = { { -1, 0 }, { 1, 0 },{ 0, 1 }, { 0, -1 } };double mnx = 0, mxx = 0, mny = 0, mxy = 0;for (int i = 0; i < n; i++) {double a = coordinates[i][0];double b = coordinates[i][1];if (a == 0) {mny = Math.min(mny, b);mxy = Math.max(mxy, b);} else {mnx = Math.min(mnx, a);mxx = Math.max(mxx, a);}}double mx = Math.max(Math.abs(mxx - mnx),Math.abs(mny - mxy));double q1 = Math.sqrt(mxx * mxx + mxy * mxy);double q2 = Math.sqrt(mnx * mnx + mxy * mxy);double q3 = Math.sqrt(mnx * mnx + mny * mny);double q4 = Math.sqrt(mxx * mxx + mny * mny);System.out.println(String.format("%.10f",Math.max(mx, Math.max(q1, Math.max(q2,Math.max(q3, q4))))));}}
C++
#include <bits/stdc++.h>using namespace std;int main(){int n = 4;vector<vector<double>> coordinates = {{-1, 0},{1, 0},{0, 1},{0, -1}};double mnx, mxx, mny, mxy;for (int i = 0; i < n; i++){double a = coordinates[i][0];double b = coordinates[i][1];if (a == 0){mny = min(mny, b);mxy = max(mxy, b);}else{mnx = min(mnx, a);mxx = max(mxx, a);}}double mx = max(abs(mxx - mnx), abs(mny - mxy));double q1 = sqrt(mxx * mxx + mxy * mxy);double q2 = sqrt(mnx * mnx + mxy * mxy);double q3 = sqrt(mnx * mnx + mny * mny);double q4 = sqrt(mxx * mxx + mny * mny);printf("%.10f", max(mx, max(q1, max(q2, max(q3, q4)))));return 0;}
No comments:
Post a Comment