C++ program to count at least how many operations needed for given conditions

C++Server Side ProgrammingProgramming

Suppose we have an array A with N elements. In each operation, we pick an element and increase or decrease it by 1. We have to find at least how many operations are needed to satisfy following conditions −

• For every i in range 1 to n, the sum of the terms from 1st through ith term is not 0

• For every i in range 1 to n - 1, the sign of the terms from the 1st through ith term is different from sign of the sum of the terms from the 1st through (i+1)th term.

So, if the input is like A = [1, -3, 1, 0], then the output will be 4, because we can transform the sequence like 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1.

Steps

To solve this, we will follow these steps −

n := size of A
ret := 0
sum := 0
for each ai in A, do
nsum := sum + ai
if s > 0, then:
if nsum <= 0, then:
ret := ret + |nsum|
ai := ai + |nsum|
Otherwise
if nsum >= 0, then:
ret := ret + nsum + 1
ai := ai - (nsum + 1)
sum := sum + ai
s := s * -1
return ret

Example

Let us see the following implementation to get better understanding −

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

int util(vector<int> A, int s){
int n = A.size();
int ret = 0;
int sum = 0;
for (int ai : A){
int nsum = sum + ai;
if (s > 0){
if (nsum <= 0){
ret += abs(nsum) + 1;
ai = ai + abs(nsum) + 1;
}
} else{
if (nsum >= 0){
ret += nsum + 1;
ai = ai - (nsum + 1);
}
}
sum += ai;
s *= -1;
}
return ret;
}
int solve(vector<int> A){
int res = min(util(A, 1), util(A, -1));
return res;
}
int main(){
vector<int> A = { 1, -3, 1, 0 };
cout << solve(A) << endl;
}

Input

{ 1, -3, 1, 0 }

Output

4
Updated on 03-Mar-2022 06:00:04