Find the maximum possible distance from origin using given points

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 <bits/stdc++.h>using namespace std;  // Function to find the maximum possible// distance from origin using given points.void Max_Distance(vector<pair<int, int> >& xy, int n){    // Sort the points with their tan angle    sort(xy.begin(), xy.end(), [](const pair<int, int>&l,                                  const pair<int, int>& 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 <i + n; j++) {            x += xy[j].first;            y += xy[j].second;            res = max(res, x * x + y * y);        }    }      // Print the required answer    cout << fixed << setprecision(2) << sqrtl(res);}  // Driver codeint main(){    vector<pair<int, int>> vec = { { 1, 1 },                                    { 2, 2 },                                    { 3, 3 },                                    { 4, 4 } };      int n = vec.size();      // Function call    Max_Distance(vec, n);      return 0;} |
Java
// Java implementation of the approachÂ
import java.util.*;Â
class GFG {Â
    // Function to find the maximum possible    // distance from origin using given points.    static void    Max_Distance(ArrayList<ArrayList<Integer> > xy, int n)    {Â
        // Sort the points with their tan angle        Collections.sort(            xy, new Comparator<ArrayList<Integer> >() {                @Override                public int compare(ArrayList<Integer> x,                                   ArrayList<Integer> y)                {                    return (int)((Math.atan2(x.get(1),                                             x.get(0)))                                 - (Math.atan2(y.get(1),                                               y.get(0))));                }            });Â
        // Push the whole vector        for (int i = 0; i < n; i++)            xy.add(xy.get(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 < i + n; j++) {                x += xy.get(j).get(0);                y += xy.get(j).get(1);                res = Math.max(res, x * x + y * y);            }        }Â
        // Print the required answer        System.out.println(            (double)Math.round(Math.sqrt(res) * 100) / 100);    }Â
    // Driver code    public static void main(String[] args)    {        ArrayList<ArrayList<Integer> > vec            = new ArrayList<ArrayList<Integer> >();Â
        ArrayList<Integer> a1 = new ArrayList<Integer>();        a1.add(1);        a1.add(1);        vec.add(a1);Â
        ArrayList<Integer> a2 = new ArrayList<Integer>();        a2.add(2);        a2.add(2);        vec.add(a2);Â
        ArrayList<Integer> a3 = new ArrayList<Integer>();        a3.add(3);        a3.add(3);        vec.add(a3);Â
        ArrayList<Integer> a4 = new ArrayList<Integer>();        a4.add(4);        a4.add(4);        vec.add(a4);Â
        int n = 4;Â
        // Function call        Max_Distance(vec, n);    }}Â
// This code is contributed by phasing17 |
Python3
# Python3 implementation of the approachfrom math import *Â
# Function to implement the custom sort def myCustomSort(l):Â Â Â Â return atan2(l[1], l[0]);Â
# Function to find the maximum possible# distance from origin using given points.def Max_Distance(xy, n):Â
    # Sort the points with their tan angle    xy.sort(key = myCustomSort);Â
    # Push the whole vector    xy += xyÂ
    # To store the required answer    res = 0;Â
    # Find the maximum possible answer    for i in range(n):        x = 0        y = 0        for j in range(i, i + n):            x += xy[j][0];            y += xy[j][1];            res = max(res, x * x + y * y);             # Print the required answer    print(round(res ** 0.5, 2)) Â
# Driver codevec = [[1, 1], [2, 2], [3, 3], [4, 4]];n = len(vec)Â
# Function callMax_Distance(vec, n);Â
# The code is contributed by phasing17 |
C#
// C# implementation of the approachusing System;using System.Linq;using System.Collections.Generic;Â
class GFG{Â
  // Function to find the maximum possible  // distance from origin using given points.  static void Max_Distance(List<int[]> xy, int n)  {Â
    // Sort the points with their tan angle    xy = xy.OrderBy(x => Math.Atan2(x[1], x[0]))      .ToList();Â
    // Push the whole vector    for (int i = 0; i < n; i++)      xy.Add(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 < i + n; j++) {        x += xy[j][0];        y += xy[j][1];        res = Math.Max(res, x * x + y * y);      }    }Â
    // Print the required answer    Console.WriteLine(Math.Round(Math.Sqrt(res), 2));  }Â
  // Driver code  public static void Main(string[] args)  {    List<int[]> vec = new List<int[]>();    vec.Add(new[] { 1, 1 });    vec.Add(new[] { 2, 2 });    vec.Add(new[] { 3, 3 });    vec.Add(new[] { 4, 4 });Â
    int n = vec.Count;Â
    // Function call    Max_Distance(vec, n);  }}Â
// This code is contributed by phasing17 |
Javascript
// JavaScript implementation of the approachÂ
// Function to implement the custom sort function myCustomSort(l, r){Â Â Â Â return Math.atan2(l[1], l[0]) < Math.atan2(r[1], r[0]);}Â
// Function to find the maximum possible// distance from origin using given points.function Max_Distance(xy, n){    // Sort the points with their tan angle    xy.sort(myCustomSort);Â
    // Push the whole vector    for (let i = 0; i < n; i++)        xy.push(xy[i]);Â
    // To store the required answer    let res = 0;Â
    // Find the maximum possible answer    for (let i = 0; i< n; i++) {        let x = 0, y = 0;        for (let j = i; j <i + n; j++) {            x += xy[j][0];            y += xy[j][1];            res = Math.max(res, x * x + y * y);        }    }Â
    // Print the required answer    console.log(Math.sqrt(res).toFixed(2));Â
}Â
// Driver codelet vec = [[1, 1],           [2, 2],           [3, 3],           [4, 4]];Â
let n = vec.length;Â
// Function callMax_Distance(vec, n);Â
// The code is contributed by Gautam goel (gautmgoel962) |
14.14
Â
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



