You have an integer βNβ and an array βXβ of βNβ integers. You need to maximize the value of the array, which is equal to β '(X[i] - i)^2' from βiβ in the range β[0, N-1]β. To do this, you can rearrange the elements of the given array.
Determine the maximum value of the array you can get after rearranging the array βXβ elements.
Example:'N' = 3, βX' = [1,2,1]
If we rearrange our array 'X' to '[2, 1, 1]' .
Then our answer will be (0-2)^2 + (1-1)^2 + (1-2)^2 = 4 + 0 + 1 = 5.
For array β[1, 1, 2]β value will be equal to β1 + 0 + 0 = 1β.
For array β[1, 2, 1]β value will be equal to β1 + 1 + 1 = 3β.
The first line contains an integer 'T', which denotes the number of test cases to be run. Then the test cases follow.
The first line of each test case contains an integer 'Nβ.
The second line contains N integers, denoting the array βXβ value.
Output format:
For each test case, return the maximum array value for the given array βXβ.
Note:
You donβt need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^4
1<= X[i] <= 10^5
Time Limit: 1 sec
2
2
1 2
3
1 1 1
4
2
For test case 1:
From this array, we can have 2 arrays i.e. β[1,2]β and β[2,1]β
For β[1,2]β the value will be equal to β (1-0)^2 + (2-1)^2β which is equal to 2.
For β[2,1]β the value will be equal to β (2-0)^2 + (1-1)^2β which is equal to 4.
Hence answer is β4β
For test case 2:
In this case, there is only one array you can get after rearranging elements of βXβ.
For array β[1,1,1]β answer will be β1+0+1=2β.
Hence the answer is β2β.
2
3
1 2 3
3
10 12 3
11
226
'(X[i] - i)' ^ 2 = 'X[i]*X[i]' + 'i*i' - '2*X[i]*i', now solve the summation of these separately.
Approach:
Algorithm:
O(N*logN), where βNβ is the length of the array βXβ.
Since we are sorting an array of length βNβ, which takes O(NlogN) time, the rest operations are performed in O(N) or O(1) time. Hence, our time complexity is O(NlogN).
O(1)
Since we are only using constant extra space, the Space Complexity is O(1).