# Minimum penalty

Practice

Author: Aryan KD
Tester: Aryan KD
Editorialist: Aryan KD

# DIFFICULTY:

CAKEWALK, SIMPLE, EASY.

Math .

# PROBLEM:

Chef has given N number of element , he has to arrange the element in some order that penalty occurs is minimum .

for example:

N=3

2 1 3

O/P = 2

In above example minimum penalty of 1,2,3 is abs(2-1)+abs(3-2) = 2

# EXPLANATION:

In above example chef has to find minimum penalty occurs if the given number is in sorted order and then take abs of the two conjugate number and sum it then we will get our ans

for example
N=3

2 1 3

O/P = 2

In above example minimum penalty of 1,2,3 is abs(2-1)+abs(3-2) = 2

lets take another example

``````5
``````

3 -2 1 4 5

The order that occur with minimum penalty is -2, 1, 3, 4, 5 the penalty is

abs(5-4)+ abs(4-3)+ abs(3-1) + abs(1-(-2))= 1+1+2+3 = 7

in above two example first we have to sort the array then find it .

# SOLUTIONS:

Setter's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int sum=0;
sort(a,a+n);
for(int i=n-1;i>0;i–){
sum+=abs(a[i]-a[i-1]);
}
cout<<sum;
}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}

Tester's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int sum=0;
sort(a,a+n);
for(int i=n-1;i>0;i–){
sum+=abs(a[i]-a[i-1]);
}
cout<<sum;
}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}

Editorialist's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int sum=0;
sort(a,a+n);
for(int i=n-1;i>0;i–){
sum+=abs(a[i]-a[i-1]);
}
cout<<sum;
}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}