
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Flip to Zeros in C++
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
#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
- Related Articles
- Flip String to Monotone Increasing in C++
- bitset::flip() in C++ STL
- Random Flip Matrix in C++
- Flip Game II in C++
- Flip Equivalent Binary Trees in C++
- Conversion of SR Flip-Flop to JK Flip-Flop
- Flip-flop types and their Conversion in C++
- Remove Trailing Zeros from string in C++
- Count Pairs of Consecutive Zeros in C++
- Count minimum bits to flip such that XOR of A and B equal to C in C++
- How to flip an image in Node Jimp?
- How to flip an image in OpenCV Python?
- Conversion of JK Flip-Flop into T Flip-Flop
- Program to find trailing zeros in factorial of n in C++?\n
- 123 Number Flip in Python
