Flip to Zeros in C++

C++Server Side ProgrammingProgramming

Suppose we have one integer array called nums and this contains 0s and 1s. Suppose we have an operation where we pick an index i in nums and flip element at index i as well as all numbers to the right of i. We have to find the minimum number of operations required to make nums contain all 0s.

So, if the input is like [1,0,1], then the output will be 3, operation on index 0, it will convert [0,1,0], then on index 1 [0,0,1], then index 2, [0,0,0].

To solve this, we will follow these steps −

• n := size of nums

• Define an array op of size n

• ret := 0

• for initialize i := 0, when i < size of nums, update (increase i by 1), do −

• if i - 1 >= 0, then −

• op[i] := op[i] + op[i - 1]

• if (nums[i] + op[i]) & 1 is non-zero, then −

• (increase op[i] by 1)

• (increase ret by 1)

Let us see the following implementation to get better understanding −

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(vector<int>& nums) {
int n = nums.size();
vector<int> op(n);
int ret = 0;
for (int i = 0; i < nums.size(); i++) {
if (i - 1 >= 0) {
op[i] += op[i - 1];
}
if ((nums[i] + op[i]) & 1) {
op[i]++;
ret++;
}
}
return ret;
}
};
main() {
Solution ob;
vector<int> v = {1,0,1};
cout << (ob.solve(v));
}

Input

{1,0,1}

Output

3
Published on 02-Sep-2020 11:33:59
Advertisements