Problem Statement:
Samu had got N fruits. Sweetness of ith fruit is given by A[i]. Now she wants to eat all the fruits , in such a way that total taste is maximised.
Total Taste is calculated as follow (Assume fruits sweetness array uses 1-based indexing) :
int taste=0; for(int i=2;i<=N;i++){ if (A[i]-A[i-1] >= 0){ taste = taste + i*(A[i]-A[i-1]); } else{ taste = taste + i*(A[i-1]-A[i]); } }
So, obviously the order in which she eat the fruits changes the Total taste. She can eat the fruits in any order. Also once she start eating a fruit she will finish that one before moving to some other fruit.
Now she got confused in deciding the order in which she should eat them so that her Total taste is maximized. So she ask for help from you. Help her find the maximum taste she can have , if she can eat the fruits in any order.
Input Format:
First line contain number of test cases T. First line of each test case contains N, denoting the number of fruits. Next line contain N space separated integers denoting the sweetness of each fruit.
Output Format:
For each test case you need to print the maximum taste Samu can have by eating the fruits in any order she want to.
Constraints:
\$1 \le T \le 10\$ \$1 \le N \le 15\$
Sweetness of each fruit, A[i] lies between 1 to 100 for 1 ≤ i ≤ N
Sample Input:
1 3 2 5 4
Sample Output:
13
Explanation:
[2,4,5] -> 2*(2) + 3*(1) = 7 [2,5,4] -> 2*(3) + 3*(1) = 9 [5,4,2] -> 2*(1) + 3*(2) = 8 [5,2,4] -> 2*(3) + 3*(2) = 12 [4,5,2] -> 2*(1) + 3*(3) = 11 [4,2,5] -> 2*(2) + 3*(3) = 13
The maximum is 13 that can be obtained by eating the fruits according to sweetness order [4,2,5].
from itertools import permutations
for _ in xrange(int(raw_input())):
n=int(raw_input())
val=map(int,raw_input().split())
max_ = 0
for A in permutations(val):
taste=0;
for i in xrange(1,len(A)):
taste = taste + (i+1)*abs(A[i]-A[i-1])
max_= max(max_,taste)
print max_