
- 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
Maximum difference of zeros and ones in binary string - (O(n) time) in C++
Given the task is to find a sub-string from a given binary string and then the maximum difference between the number of zeroes and the ones.
Let’s now understand what we have to do using an example −
Input
str = “10010110”
Output
2
Explanation
In the sub-array from the position 1 to 4 (“0010”), the difference between the zeros and ones = 3 – 1 = 2 which is the maximum that can be found.
Input
str = “00000”
Output
5
Approach used in the below program as follows
In main() function create a string str to store the binary string. Also declare an array int arr[str.length()+1];
Set all elements of arr[] = 0 by using memset(arr,0,sizeof(arr));
Loop from j = 1 till j<= str.length()
Check if(memset(arr,0,sizeof(arr)), if so then put arr[j]=max(arr[j-1]-1,-1);
Else put arr[j]=max(arr[j-1]+1,1);
Outside the loop print the maximum number by using *max_element(arr+1, arr+str.length()+1);
Example
#include<bits/stdc++.h> using namespace std; int main(){ string str = "10010110"; int arr[str.length()+1]; memset(arr,0,sizeof(arr)); for(int j=1;j<=str.length();j++){ if(str[j-1]=='1') arr[j]=max(arr[j-1]-1,-1); else arr[j]=max(arr[j-1]+1,1); } cout<<*max_element(arr+1,arr+str.length()+1); return 0; }
Output
2
- Related Articles
- Maximum difference of zeros and ones in binary string in C++
- Find the maximum repeating number in O(n) time and O(1) extra space in Python
- Maximum number of ones in a N*N matrix with given constraints in C++
- Find median of BST in O(n) time and O(1) space in Python
- Find median of BST in O(n) time and O(1) space in C++
- Count of substrings of a binary string containing K ones in C++
- Maximum Number of Ones in C++
- Find maximum in a stack in O(1) time and O(1) extra space in C++
- Print left rotation of array in O(n) time and O(1) space in C Program.
- Maximum consecutive one’s (or zeros) in a binary circular array in C++
- Rearrange positive and negative numbers in O(n) time and O(1) extra space in C++
- Count frequencies of all elements in array in O(1) extra space and O(n) time in C++
- Find duplicates in O(n) time and O(1) extra space - Set 1 in C++
- Count Fibonacci numbers in given range in O(Log n) time and O(1) space in C++
- C++ Program to find the maximum subarray sum O(n^2) time (naive method)
