tg-me.com/Competitive_Programming_Cpp/42
Last Update:
Problem: Let A be an unsorted array of n floating numbers. Propose an O(n) time algorithm to compute the (floating-point) number x (not necessarily an element of A) for which max|A[i] - x| is as small as possible for all 1 <= i <= n. (Here |y| means absolute value of y)
Solution: The problem statement can be interpreted as finding a point x such that it's distance from the farthest point is minimized (since, |A[i] - x| is given which is actually distance between two point). Note: we don't need to minimize distance from every point, we just need to minimize the distance of the point which is farthest to it. So we try to put our x as close to the farthest point. But in doing so the point which is near may go far. So the optimal solution is finding the minimum point in the array A (let it be named MN) and finding the maximum point of A (let it be named MX) and the result is the mid-point of these two points, i.e x=(MN+MX)/2. Note: All other point between MN and MX will have distance lesser hence we do not bother it. We could not get more optimal point than this one. Now, MX and MN can be easily determined by travelling once the array. Hence the time complexity is O(n).
Happy Coding!!!
BY Competitive Programming
Warning: Undefined variable $i in /var/www/tg-me/post.php on line 280
Share with your friend now:
tg-me.com/Competitive_Programming_Cpp/42