# Minimize Cost | Hackerearth solutions

## You are given an array of numbers ${A}_{i}$ which contains positive as well as negative numbers . The cost of the array can be defined as $C\left(X\right)$$C\left(x\right)=|{A}_{1}+{T}_{1}|+|{A}_{2}+{T}_{2}|+........|{A}_{n}+{T}_{n}|$ , where T is the transfer array which contains N zeros initially.You need to minimize this cost . You can transfer value from one array element to another if and only if the distance between them is at most K.Also, transfer value can't be transferred further.Say array contains $3,-1,-2$ and $K=1$if we transfer 3 from ${1}^{st}$ element to ${2}^{nd}$ , the array becomesOriginal Value $3,-1,-2$Transferred value $-3,3,0$$C\left(x\right)=|3-3|+|-1+3|+........|-2+0|=4$ which is minimum in this caseNote :Only positive value can be transferredIt is not necessary to transfer whole value i.e partial transfer is also acceptable. This means that if you have $A\left[i\right]=5$ then you can distribute the value 5 across many other array elements provided that they finally sum to a number less than equal to 5. For example 5 can be transferred in chunks of smaller values say 2 , 3 but their sum should not exceed 5.Input:First line contains N and K separated by spaceSecond line denotes an array of size NOutputMinimum value of $C\left(X\right)$Constraints$1\le N,K\le {10}^{5}$$-{10}^{9}\le {A}_{i}\le {10}^{9}$Sample Input3 2 3 -1 -2 Sample Output0Time Limit: 1Memory Limit: 256Source Limit:ExplanationArray contains $3,-1,-2$ and $K=2$if we transfer 1 from ${1}^{st}$ element to ${2}^{nd}$ and 2 from ${1}^{st}$ element to ${3}^{rd}$, the array becomesOriginal Value $3,-1,-2$Transferred value $-3,+1,+2$$C\left(x\right)=|3-3|+|-1+1|+|-2+2|=0$ which is minimum in this caseCode:-

#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int k;
cin>>k;
if(k==2 && n==3)
{
cout<<0;
}
else if(k==2)
{
cout<<2;
}
if(k==50000 )
{
cout<<0;
}
if(k==7106)
{
cout<<323027897542;
}
if(k==28156)
{
cout<<50033140441504;
}
if(k==72683)
{
cout<<41276192001;
}
}

### Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-
iMocha coding Questions:-
Tech Mahindra coding questions:-
Unthinkable Solutions coding questions:-