![]() |
VOOZH | about |
Given an array arr[]. The task is t find the value of X such that the result of the expression (A[1] - X)^2 + (A[2] - X)^2 + (A[3] - X)^2 + ... (A[n-1] - X)^2 + (A[n] – X)^2 is minimum possible.
Examples :
Input : arr[] = {6, 9, 1, 6, 1, 3, 7}
Output : 5
Input : arr[] = {1, 2, 3, 4, 5}
Output : 3
Approach:
We can simplify the expression that we need to minimize. The expression can be written as
(A[1]^2 + A[2]^2 + A[3]^2 + … + A[n]^2) + nX^2 – 2X(A[1] + A[2] + A[3] + … + A[n])
On differentiating the above expression, we get
2nX - 2(A[1] + A[2] + A[3] + … + A[n])
We can denote the term (A[1] + A[2] + A[3] + … + A[n] ) as S. We get
2nX - 2S
Putting 2nX - 2S = 0, we get
X = S/N
Below is the implementation of the above approach:
5
Time Complexity: O(n)
Auxiliary Space: O(1)