Find the maximum possible distance from origin using given points

• Difficulty Level : Basic
• Last Updated : 19 Jan, 2022

Given N 2-Dimensional points. The task is to find the maximum possible distance from the origin using given points. Using the ith point (xi, yi) one can move from (a, b) to (a + xi, b + yi)
Note: N lies between 1 to 1000 and each point can be used at most once.
Examples:

Input: arr[][] = {{1, 1}, {2, 2}, {3, 3}, {4, 4}}
Output: 14.14
The farthest point we can move to is (10, 10).
Input: arr[][] = {{0, 10}, {5, -5}, {-5, -5}}
Output: 10.00

Approach: The key observation is that when the points are ordered by the angles their vectors make with the x-axis, the answer will include vectors in some contiguous range. A proof of this fact can be read from here. Then, the solution is fairly easy to implement. Iterate over all possible ranges and compute the answers for each of them, taking the maximum as the result. When implemented appropriately, this is an O(N2) approach.
Below is the implementation of the above approach:

CPP

 // C++ implementation of the approach#include using namespace std; // Function to find the maximum possible// distance from origin using given points.void Max_Distance(vector >& xy, int n){    // Sort the points with their tan angle    sort(xy.begin(), xy.end(), [](const pair&l,                                  const pair& r) {        return atan2l(l.second, l.first)               < atan2l(r.second, r.first);    });     // Push the whole vector    for (int i = 0; i < n; i++)        xy.push_back(xy[i]);     // To store the required answer    int res = 0;     // Find the maximum possible answer    for (int i = 0; i< n; i++) {        int x = 0, y = 0;        for (int j = i; j > vec = { { 1, 1 },                                    { 2, 2 },                                    { 3, 3 },                                    { 4, 4 } };     int n = vec.size();     // Function call    Max_Distance(vec, n);     return 0;}
Output:
14.14

Time Complexity: O(n^2)

Auxiliary Space: O(1)

My Personal Notes arrow_drop_up