**Link**

https://codefights.com/tournaments/gL4JNbYY5yuXpnNMF/C

**Description**

Given a sorted array of integers `A`

, find such an integer `x`

that ∑(A[i] – x)^{2} over all `i`

has the *minimum possible value*. If there are several possible answers, output the *smallest* one.

**Example**

For `A = [2, 4, 7]`

, the output should be

`squaresSumMinimization(A) = 4`

.

**Input/Output**

**[time limit] 3000ms (cs)**

**[input] array.integer A**A non-empty array of integers, sorted in ascending order.*Constraints:*

`1 ≤ A.length ≤ 5`

,

`-25 ≤ A[i] ≤ 25`

.**[output] integer**

**Solution(C#)**

int squaresSumMinimization(int[] A) { var minimum = Int32.MaxValue; var element = 0; for (var i = -25; i < 26; i++) { var sum = 0; for (var j = 0; j < A.Length; j++) { sum += (int)Math.Pow(A[j] - i,2); } if (sum < minimum) { minimum = sum; element = i; } } return element; }

Advertisements