title: Find largest total distance across 5 points in N points dataset
body: <p>The problem I'm trying to solve involves a dataset of roughly 5000 GPS points and the task to find the 5 points within that dataset that result in the largest overall distance.</p>
  
  <p><a href="https://i.stack.imgur.com/PNcE0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PNcE0.png" alt="Sketch"></a></p>
  
  <p>(Note that Start and End are not necessarily at the same location)</p>
  
  <p>The naive solution would be five nested loops that iterate over all the points in the dataset until the largest total distance is found, but that is unpractical given that the distance calculation is somewhat slow:</p>
  
  <pre><code>for (i = 0; i &lt; points.length; i++) {
    pointA = points[i];
  
    for (j = i; j &lt; points.length; j++) {
      pointB = points[j];
      distanceAB = distance(pointA, pointB);
  
      for (k = j; k &lt; points.length; k++) {
        pointC = points[k];
        distanceBC = distance(pointB, pointC);
  
        // ...
  
        score = distanceAB + distanceBC + distanceCD + distanceDE;
        if (score &gt; winner.score) {
          // save new winner
        }
      }
    }
  }
  </code></pre>
  
  <p>Is there a solution to this problem that needs to do less work?</p>