# How can I find the k-nearest neighbors for a collection of linear time series data?

I need to figure out how to determine the nearest neighbors of an "optimal" line, as illustrated in a simplified figure, linked below.

The blue, orange, green, and purple lines represent the best fit to a time series of ~50-100 data points. The desired profile (red dashed line) represents the optimal linear trajectory:

Is there a reliable way by which I can calculate which is nearest to the optimal line via k-nearest neighbors? Or will I need to write my own algorithm that determines the curve that has the least sum of squares? It seems that there might even be a way to treat the points belonging to a single curve as a "cluster" and perform k-means clustering to find the least squares fit?

DESIRED GOAL: In any case, if I were to set k=1, I'd like the algorithm to select the green time series. And if k=2, I'd like it to select both the orange and green lines (and automatically calculate the average of their labeled values).

I'm not sure if i'd need to use the raw data in aggregate or use fitted lines for each of the time series.

Ideally, I'd like to use R for this project, but have just begun learning python.

Hopefully I've provided enough info to make things understandable.