Header Ads Widget

Minimize Cost | Hackerearth solutions

 Program:-

You are given an array of numbers Ai which contains positive as well as negative numbers . The cost of the array can be defined as C(X)

C(x)=|A1+T1|+|A2+T2|+........|An+Tn| , 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 1st element to 2nd , the array becomes

Original Value 3,1,2

Transferred value 3,3,0

C(x)=|33|+|1+3|+........|2+0|=4 which is minimum in this case

Note :

Only positive value can be transferred

It is not necessary to transfer whole value i.e partial transfer is also acceptable. This means that if you have A[i]=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 space

Second line denotes an array of size N

Output

Minimum value of C(X)

Constraints

1N,K105

109Ai109

Sample Input
3 2
3 -1 -2
Sample Output
0
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

Array contains 3,1,2 and K=2

if we transfer 1 from 1st element to 2nd and 2 from 1st element to 3rd, the array becomes

Original Value 3,1,2

Transferred value 3,+1,+2

C(x)=|33|+|1+1|+|2+2|=0 which is minimum in this case



Code:-

#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:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

Post a Comment

0 Comments