Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Minimum splits in a binary string such that every substring is a power of 4 or 6.
Next article icon

Split a Binary String such that count of 0s and 1s in left and right substrings is maximum

Last Updated : 31 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings.

Examples:

Input: str = “000111” 
Output: 6 
Explanation: 
Splitting the binary string into “000” and “111”. 
Count of 0s in the left substring of the string = 3 
Count of 1s in the right substring of the string = 3 
Therefore, the sum of the count of 0s in the left substring of the string and the count of 1s in the right substring of the string = 3 + 3 = 6. 
 

Input: S = “1111” 
Output: 3 
Explanation: 
Splitting the binary string into “1” and “111”. 
Count of 0s in the left substring of the string = 0 
Count of 1s in the right substring of the string = 3 
Therefore, the sum of the count of 0s in the left substring of the string and the count of 1s in the right substring of the string = 0 + 3 = 3. 
 

Approach: Follow the steps below to solve the problem:

  1. Initialize a variable, say res, to store the maximum sum of count of 0s in left substring and count of 1s in the right substring.
  2. Initialize a variable, say cntOne, to store count of 1s in the given binary string.
  3. Traverse the binary string and for each character, check if it is ‘1’ or not. If found to be true, then increment the value of cntOne by 1.
  4. Initialize two variables, say zero and one, to store the count of 0s and count of 1s till ith index.
  5. Traverse the binary string and update the value of res = max(res, cntOne – one + zero).
  6. Finally, print the value of res.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum of count  of
// 0s in the left substring and count of 1s in
// the right substring by splitting the string
int maxSumbySplittingstring(string str, int N)
{
 
    // Stores count of 1s
    // the in binary string
    int cntOne = 0;
 
    // Traverse the binary string
    for (int i = 0; i < N; i++) {
 
        // If current character is '1'
        if (str[i] == '1') {
 
            // Update cntOne
            cntOne++;
        }
    }
 
    // Stores count of 0s
    int zero = 0;
 
    // Stores count of 1s
    int one = 0;
 
    // Stores maximum sum of count of
    // 0s and 1s by splitting the string
    int res = 0;
 
    // Traverse the binary string
    for (int i = 0; i < N - 1; i++) {
 
        // If current character
        // is '0'
        if (str[i] == '0') {
 
            // Update zero
            zero++;
        }
 
        // If current character is '1'
        else {
 
            // Update one
            one++;
        }
 
        // Update res
        res = max(res, zero + cntOne - one);
    }
 
    return res;
}
 
// Driver Code
int main()
{
    string str = "00111";
    int N = str.length();
 
    cout << maxSumbySplittingstring(str, N);
 
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
import java.util.*;
class GFG
{
 
  // Function to find the maximum sum of count  of
  // 0s in the left subString and count of 1s in
  // the right subString by splitting the String
  static int maxSumbySplittingString(String str, int N)
  {
 
    // Stores count of 1s
    // the in binary String
    int cntOne = 0;
 
    // Traverse the binary String
    for (int i = 0; i < N; i++)
    {
 
      // If current character is '1'
      if (str.charAt(i) == '1')
      {
 
        // Update cntOne
        cntOne++;
      }
    }
 
    // Stores count of 0s
    int zero = 0;
 
    // Stores count of 1s
    int one = 0;
 
    // Stores maximum sum of count of
    // 0s and 1s by splitting the String
    int res = 0;
 
    // Traverse the binary String
    for (int i = 0; i < N - 1; i++) {
 
      // If current character
      // is '0'
      if (str.charAt(i) == '0') {
 
        // Update zero
        zero++;
      }
 
      // If current character is '1'
      else {
 
        // Update one
        one++;
      }
 
      // Update res
      res = Math.max(res, zero + cntOne - one);
    }
    return res;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String str = "00111";
    int N = str.length();
 
    System.out.print(maxSumbySplittingString(str, N));
  }
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to implement
# the above approach
 
# Function to find the maximum sum of count  of
# 0s in the left suband count of 1s in
# the right subby splitting the string
def maxSumbySplittingstring(str, N):
 
    # Stores count of 1s
    # the in binary string
    cntOne = 0
 
    # Traverse the binary string
    for i in range(N):
 
        # If current character is '1'
        if (str[i] == '1'):
 
            # Update cntOne
            cntOne += 1
 
    # Stores count of 0s
    zero = 0
 
    # Stores count of 1s
    one = 0
 
    # Stores maximum sum of count of
    # 0s and 1s by splitting the string
    res = 0
 
    # Traverse the binary string
    for i in range(N - 1):
 
        # If current character
        # is '0'
        if (str[i] == '0'):
 
            # Update zero
            zero += 1
 
        # If current character is '1'
        else:
 
            # Update one
            one += 1
 
        # Update res
        res = max(res, zero + cntOne - one)
    return res
 
# Driver Code
if __name__ == '__main__':
    str = "00111"
    N = len(str)
 
    print (maxSumbySplittingstring(str, N))
 
    # This code is contributed by mohit kumar 29.
 
 

C#




// C# program to implement
// the above approach
using System;
public class GFG
{
 
  // Function to find the maximum sum of count  of
  // 0s in the left subString and count of 1s in
  // the right subString by splitting the String
  static int maxSumbySplittingString(String str, int N)
  {
 
    // Stores count of 1s
    // the in binary String
    int cntOne = 0;
 
    // Traverse the binary String
    for (int i = 0; i < N; i++)
    {
 
      // If current character is '1'
      if (str[i] == '1')
      {
 
        // Update cntOne
        cntOne++;
      }
    }
 
    // Stores count of 0s
    int zero = 0;
 
    // Stores count of 1s
    int one = 0;
 
    // Stores maximum sum of count of
    // 0s and 1s by splitting the String
    int res = 0;
 
    // Traverse the binary String
    for (int i = 0; i < N - 1; i++) {
 
      // If current character
      // is '0'
      if (str[i] == '0') {
 
        // Update zero
        zero++;
      }
 
      // If current character is '1'
      else {
 
        // Update one
        one++;
      }
 
      // Update res
      res = Math.Max(res, zero + cntOne - one);
    }
    return res;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    String str = "00111";
    int N = str.Length;
 
    Console.Write(maxSumbySplittingString(str, N));
  }
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to find the maximum sum of count  of
// 0s in the left substring and count of 1s in
// the right substring by splitting the string
function maxSumbySplittingstring(str, N)
{
 
    // Stores count of 1s
    // the in binary string
    var cntOne = 0;
 
    // Traverse the binary string
    for(var i = 0; i < N; i++) {
 
        // If current character is '1'
        if (str[i] == '1') {
 
            // Update cntOne
            cntOne++;
        }
    }
 
    // Stores count of 0s
    var zero = 0;
 
    // Stores count of 1s
    var one = 0;
 
    // Stores maximum sum of count of
    // 0s and 1s by splitting the string
    var res = 0;
 
    // Traverse the binary string
    for (var i = 0; i < N - 1; i++) {
 
        // If current character
        // is '0'
        if (str[i] == '0') {
 
            // Update zero
            zero++;
        }
 
        // If current character is '1'
        else {
 
            // Update one
            one++;
        }
 
        // Update res
        res = Math.max(res, zero + cntOne - one);
    }
 
    return res;
}
 
// Driver Code
var str = "00111";
var N = str.length;
document.write( maxSumbySplittingstring(str, N));
 
 
</script>
 
 
Output: 
5

 

Time complexity: O(N)
Auxiliary Space: O(1)



Next Article
Minimum splits in a binary string such that every substring is a power of 4 or 6.

A

aryan_a
Improve
Article Tags :
  • C++
  • DSA
  • Strings
  • binary-string
  • frequency-counting
  • substring
Practice Tags :
  • CPP
  • Strings

Similar Reads

  • Maximize count of 0s in left and 1s in right substring by splitting given Binary string
    Given a binary string str, the task is to split the given binary string at any index into two non-empty substrings such that the sum of counts of 0s in the left substring and 1s in the right substring is maximum. Print the sum of such 0s and 1s in the end. Examples: Input: str = "0011110011" Output:
    6 min read
  • Minimum splits in a binary string such that every substring is a power of 4 or 6.
    Given a string S composed of 0 and 1. Find the minimum splits such that the substring is a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such partitioning is possible. Examples: Input: 100110110 Output: 3 The string can be split into a minimum of three substrings
    11 min read
  • Minimum flips required in a binary string such that all K-size substring contains 1
    Given a binary string str of size N and a positive integer K, the task is to find the minimum number of flips required to make all substring of size K contain at least one '1'.Examples: Input: str = "0001", K = 2 Output: 1 Explanation: Flipping the bit at index 1 modifies str to "0101". All substrin
    11 min read
  • Split the binary string into substrings with equal number of 0s and 1s
    Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input
    8 min read
  • Count of substrings in a Binary String that contains more 1s than 0s
    Given a binary string s, the task is to calculate the number of such substrings where the count of 1's is strictly greater than the count of 0's. Examples Input: S = "110011"Output: 11Explanation: Substrings in which the count of 1's is strictly greater than the count of 0's are { S[0]}, {S[0], S[1]
    15+ min read
  • Replace '?' to convert given string to a binary string with maximum count of '0' and "10"
    Given string str, consisting of three different types of characters '0', '1' and '?', the task is to convert the given string to a binary string by replacing the '?' characters with either '0' or '1' such that the count of 0s and 10 in the binary string is maximum. Examples: Input: str = 10?0?11Outp
    4 min read
  • Maximum count of unique index 10 or 01 substrings in given Binary string
    Given a binary string str of length N, the task is to count the maximum number of adjacent pairs of form "01" or "10" that can be formed from the given binary string when one character can be considered for only one pair. Note: Adjacent pair means pair formed using adjacent characters. Examples: Inp
    5 min read
  • Count of substrings that start and end with 1 in given Binary String
    Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
    12 min read
  • Count of substrings with equal ratios of 0s and 1s till ith index in given Binary String
    Given a binary string S, the task is to print the maximum number of substrings with equal ratios of 0s and 1s till the ith index from the start. Examples: Input: S = "110001"Output: {1, 2, 1, 1, 1, 2}Explanation: The given string can be partitioned into the following equal substrings: Valid substrin
    9 min read
  • Maximum number of set bits count in a K-size substring of a Binary String
    Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = "100111010", K = 3 Output: 3 Explanation: The substring "111" contains 3 set bits. Input:S = "0000000", K = 4 Output: 0 Explanation: S doesn't
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences