This problem is basically an algorithm optimization problem.
We have a list which has n elements. for e.g. {n1,n2,n3...nk}
This list is sorted and we have to find out the number ni which is
n1<=ni<=nk
- The sum of distance of
ni
from each number is minimum.
There may be total (nk-n1+1)
possible numbers but our objective is to find out the number ni
which is
nearest to all other numbers.
Brute force approach could be iterate through n1
to nk and calculate the sum of distance
from all list numbers. This way easily we can figure out the number who is closest to all other numbers in the list.
But the problem with this approach is, it is not good in terms of time complexity. The time complexity of this approach is O(n^2)
.
I think there could be better method to do this which can solve this problem with less time complexity.
Any approach will be appreciated.