Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Maximize

Easy
0/40
Average time to solve is 25m
profile
Contributed by
1 upvote
Asked in company
Intuit

Problem statement

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’.
Detailed explanation ( Input/output format, Notes, Images )
Constraints :
1 <= T <= 10
1 <= N <= 10^4
1<= X[i] <= 10^5

Time Limit: 1 sec
Sample Input 1 :
2
2
1 2  
3
1 1 1 
Sample Output 1 :
4
2
Explanation Of Sample Input 1 :
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’.
Sample Input 2:
2
3
1 2 3
3
10 12 3
Sample Output 2:
11
226
Full screen
Console