# Daily HackerRank Challenge - Day 16

Daily HackerRank Challenge (30 Part Series)

This is a series of Daily HackerRank Challenge. Each day I show the some solutions written in C++.

# Minimum Absolute Difference in an Array

Sample Input

3
3 -7 0


Sample Output

3


The first approach is to loop through the array between 0..n-1, 1..n-2, and 2..n-3, and so on. However, this approach is not ideal because we are finding all the differences. Instead,
We can sort the array first because the values that are closest to one another produces the least difference such as (10,8) < (10,1). We can use C++ STL to solve this problem by calculating the difference between each adjacent element, and returning the minimum value of the array.

Final Solution

int n;

int comp(int x, int y){
return abs(x-y);
}

int main()
{
FAST_INP;
cin >> n;
vi arr(n);
vi result(n);
REP(i,n) cin >> arr[i];
sort(arr.begin(), arr.end());
cout << *min_element(result.begin()+1, result.end());
return 0;
}


# Marc's Cakewalk

Sample Input

3
1 3 2


Sample Output

11


Since we need the minimum value, so we can sort the array in a descending order and apply the formula sum = sum + 2^i*v[i] to find out the final sum value.

sort(v.rbegin(),v.rend());
REP(i,n) sum+=pow(2,i)*v[i];
cout<<sum;


Final Solution

int n;
ll sum=0;

int main()
{
FAST_INP;
cin>>n;
vi v(n);
REP(i,n) cin>>v[i];
sort(v.rbegin(),v.rend());
REP(i,n) sum+=pow(2,i)*v[i];
cout<<sum;
return 0;
}


# Luck Balance

We sort the array in a descending order and assume Lena loses all non-important competition so that we can have maximum luck. If it it an important contest, we add T[i] to her luck and deduct k by 1 because losing a contest means increasing her luck. The more L[i] it provides , the more luck she will get. If she cannot lose anymore, deduct the luck by T[i].

Final Solution

int n,k,ans=0;

int main()
{
FAST_INP;
cin>>n>>k;
vector<vector<int>> c(n);
for (int i=0; i<n; i++) {
c[i].resize(2);
for (int j = 0; j < 2; j++) cin >> c[i][j];
}
sort(c.rbegin(),c.rend());
REP(i,n){
if(!c[i][1]){
// not important
ans+=c[i][0];
}else{
if(k){
ans+=c[i][0]; // lose
k--;
}
else ans-=c[i][0];    // win
}
}
cout << ans;
return 0;
}


# Complete Code

Check out the complete code via below links

Daily HackerRank Challenge (30 Part Series)

Posted on by:

### Wing-Kam

Consultant by day. Developer by night. AWS certified. Exploring #CloudNative currently.