You are given an array of numbers
, 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 and
if we transfer 3 from element to , the array becomes
Original Value
Transferred value
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 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 k, vector<int> arr){int n = arr.size();long long res = 0;int i, j;for (i = j = 0; i < n; i++){//if the current element is//less than zero or zeroif (arr[i] <= 0)continue;while (i - j > k)++j;while (arr[i] != 0 && (i + k) >= min(n - 1, j)){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 = 0; i < n; i++)res += abs(arr[i]);return res;}int main(){int n = 3;long long k = 2;vector<int> arr = {3, -1, -2};cout << minimizeCost(k, arr) << "\n";return 0;}
No comments:
Post a Comment