1. /*
  2. // Sample code to perform I/O:
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9. int num;
  10. cin >> num; // Reading input from STDIN
  11. cout << "Input number is " << num << endl; // Writing output to STDOUT
  12. }
  13.  
  14. // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
  15. */
  16.  
  17. // Write your code here
  18. #include<bits/stdc++.h>
  19. using namespace std;
  20.  
  21. long int min_cost(int n,int k,int *a){
  22. long int cost = 0;
  23. deque<int> negative_indices;
  24. vector<int> postive_indices;
  25. //indexes of negative value
  26. for(int i=0;i<n;i++)
  27. if(a[i]<0)
  28. negative_indices.push_back(i);
  29. else
  30. postive_indices.push_back(i);
  31. int neg_size = negative_indices.size();
  32. int pos_size = negative_indices.size();
  33. if(pos_size==0||neg_size==0){
  34. for(int i=0;i<n;i++)
  35. cost+=abs(a[i]);
  36. return cost;
  37. }
  38. for(int i:postive_indices){
  39. for(int j:negative_indices){
  40. if(a[i]<=0||i+k<j)
  41. break;
  42. if(a[j]>=0 || abs(i-j)>k){
  43. if(a[j]>=0)
  44. negative_indices.pop_front();
  45. continue;
  46. }
  47. int sub = min(a[i],-a[j]);
  48. a[i] -= sub;
  49. a[j] += sub;
  50. }
  51. }
  52. for(int i=0;i<n;i++)
  53. cost+=abs(a[i]);
  54. return cost;
  55. }
  56.  
  57. int main(){
  58. int n,k;
  59. cin>>n>>k;
  60. int a[n];
  61. for(int i=0;i<n;i++)
  62. cin>>a[i];
  63. cout<<min_cost(n, k, a)<<'\n';
  64. return 0;
  65. }
Language: C++17