Minimize Cost

You are given an array of numbers Awhich 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 the 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.

Example:

Input:  n = 3, k = 2, arr = {3, -1, -2}
Output: 0

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long long minimizeCost(long long kvector<intarr)
{

    int n = arr.size();
    long long res = 0;
    int ij;
    for (i = j = 0i < ni++)
    {

        //if the current element is
        //less than zero or zero
        if (arr[i] <= 0)
            continue;

        while (i - j > k)
            ++j;
        while (arr[i] != 0 && (i + k) >= min(n - 1j))
        {
            if (arr[j] > 0)
            {
                j++;
                continue;
            }
            int x = min(arr[i]abs(arr[j]));
            arr[i] -= x;
            arr[j] += x;
            if (arr[j] >= 0)
                j++;
        }
    }
    for (i = 0i < ni++)
        res += abs(arr[i]);
    return res;
}

int main()
{

    int n = 3;
    long long k = 2;

    vector<intarr = {3, -1, -2};

    cout << minimizeCost(karr<< "\n";

    return 0;
}


No comments:

Post a Comment