VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-minimum-value-of-x-for-an-expression/

⇱ Find the minimum value of X for an expression - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the minimum value of X for an expression

Last Updated : 10 Mar, 2022

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 :
 


 


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: 
 


Output: 
5

 

Time Complexity: O(n)

Auxiliary Space: O(1)
 

Comment