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
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Deletions of "01" or "10" in binary string to make it free from "01" or "10"
Next article icon

Minimize the maximum of 0s left or 1s deleted from Binary String

Last Updated : 08 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given a binary string S of size N consisting of characters 0 and/or 1. You may remove several characters from the beginning or the end of the string. The task is to find the cost of removal where the cost is the maximum of the following two values:

  • The number of characters 0 left in the string.
  • The number of characters 1 removed from the string.

Examples:

Input: S = "101110110"
Output: 1
Explanation: It is possible to remove two characters from the beginning and one character from the end. Only one 1 is deleted, only one 0 remains. So the cost is 1

Input: S = "1001001001001"
Output: 3
Explanation: It is possible to remove three characters from the beginning and six characters from the end. Two 0 remains, three 1 are deleted. So the cost is 3

Input: S = "0000111111"
Output: 0
Explanation: It is optimal to remove four characters from the beginning.

Input: S = "00000"
Output: 0
Explanation: It is optimal to remove the whole string.

Approach: The problem can be solved based on the following idea:

Say there are total X number of 0s in S. So if we do not delete any of the characters the maximum cost will be X. We have to delete some 0 to minimize the cost.

The optimal way is to delete at most X elements in total. If we delete more than X elements, there is a possibility of deleting more than X 1s which will result in more cost. Also we cannot reduce the cost by deleting more than X characters.

Proof: Say there were Y 1s deleted among the total X deleted characters. Now to reduce the cost we can only delete 0s from the string. There can at max be Y 0s that are not deleted from the string. So the present cost is max(Y, Y) = Y. If we delete those Y then no 0 will be left but already Y 1s are deleted. So the cost will be max(0, Y) = Y.

Follow the below steps to implement the idea efficiently:

  • Iterate the string and find the total count of 0s (say count0).
  • Maintain the prefix count of zero and suffix count of zeroes in two arrays (say prefixCountZero[] and suffixCountZero[]).
  • Iterate from zero to count0 and calculate the current cost as:
    • currentCost = count0 - prefixCountZero [ i - 1 ] - suffixCountZero [ n - ( count0 - i ) ]
    • The minimum of all values of currentCost will be the answer.

Below is the implementation of the above approach:

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to find the minimum cost int minCost(string s) {     int n = s.length();     int count0 = 0;     int ans = INT_MAX;     for (int i = 0; i < n; i++) {         if (s[i] == '0')             count0++;     }     vector<int> prefixCountZero(n, 0);     vector<int> suffixCountZero(n, 0);      // Loop to find the prefix count of 0     for (int i = 0; i < n; i++) {         if (i != 0)             prefixCountZero[i] = prefixCountZero[i - 1];         if (s[i] == '0')             prefixCountZero[i]++;     }      // Loop to find the suffix count of 0     for (int i = n - 1; i >= 0; i--) {         if (i != n - 1)             suffixCountZero[i] = suffixCountZero[i + 1];         if (s[i] == '0')             suffixCountZero[i]++;     }      // Loop to find the minimum cost     for (int i = 0; i <= count0; i++) {         int x;         if (i == 0) {             x = count0 - suffixCountZero[n - count0];         }         else if (i == count0) {             x = count0 - prefixCountZero[count0 - 1];         }         else {             x = count0 - prefixCountZero[i - 1]                 - suffixCountZero[n - (count0 - i)];         }         ans = min(ans, x);     }     return ans; }  // Driver code int main() {      string S = "101110110";      // Function call     cout << minCost(S);     return 0; } 
Java
// Java code to implement the approach  import java.io.*;  class GFG {      // Function to find the minimum cost     public static int minCost(String s)     {         int n = s.length();         int count0 = 0;         int ans = Integer.MAX_VALUE;         for (int i = 0; i < n; i++) {             if (s.charAt(i) == '0')                 count0++;         }         int prefixCountZero[] = new int[n];         int suffixCountZero[] = new int[n];          // Loop to find the prefix count of 0s         for (int i = 0; i < n; i++) {             if (i != 0)                 prefixCountZero[i] = prefixCountZero[i - 1];             if (s.charAt(i) == '0')                 prefixCountZero[i]++;         }          // Loop to find the suffix count of 0s         for (int i = n - 1; i >= 0; i--) {             if (i != n - 1)                 suffixCountZero[i] = suffixCountZero[i + 1];             if (s.charAt(i) == '0')                 suffixCountZero[i]++;         }          // Loop to find the minimum cost         for (int i = 0; i <= count0; i++) {             int x;             if (i == 0) {                 x = count0 - suffixCountZero[n - count0];             }             else if (i == count0) {                 x = count0 - prefixCountZero[count0 - 1];             }             else {                 x = count0 - prefixCountZero[i - 1]                     - suffixCountZero[n - (count0 - i)];             }             ans = Math.min(ans, x);         }         return ans;     }      // Driver code     public static void main(String[] args)     {         String S = "101110110";          // Function call         System.out.println(minCost(S));     } } 
Python3
# Python code to implement the approach  # Function to find the minimum cost def minCost(s):     n = len(s)     count0 = 0     ans = float('inf')     for i in range(n):         if(s[i] == '0'):             count0 += 1      prefixCountZero = [0]*n     suffixCountZero = [0]*n      # Loop to find the prefix count of 0     for i in range(n):         if(i != 0):             prefixCountZero[i] = prefixCountZero[i-1]         if(s[i] == '0'):             prefixCountZero[i] += 1      # Loop to find the suffix count of 0     for i in range(n-1, -1, -1):         if(i != n-1):             suffixCountZero[i] = suffixCountZero[i+1]         if(s[i] == '0'):             suffixCountZero[i] += 1      # Loop to find the minimum cost     for i in range(count0+1):         if(i == 0):             x = count0 - suffixCountZero[n - count0]         elif(i == count0):             x = count0 - prefixCountZero[count0 - 1]         else:             x = count0 - prefixCountZero[i-1] - suffixCountZero[n-(count0 - i)]         ans = min(ans, x)      return ans  S = "101110110"  # Function call print(minCost(S))  # This code is contributed by lokeshmvs21. 
C#
// C# code to implement the approach using System;  public class GFG {      // Function to find the minimum cost     public static int minCost(String s)     {         int n = s.Length;         int count0 = 0;         int ans = Int32.MaxValue;         for (int i = 0; i < n; i++) {             if (s[i] == '0')                 count0++;         }         int[] prefixCountZero = new int[n];         int[] suffixCountZero = new int[n];          // Loop to find the prefix count of 0s         for (int i = 0; i < n; i++) {             if (i != 0)                 prefixCountZero[i] = prefixCountZero[i - 1];             if (s[i] == '0')                 prefixCountZero[i]++;         }          // Loop to find the suffix count of 0s         for (int i = n - 1; i >= 0; i--) {             if (i != n - 1)                 suffixCountZero[i] = suffixCountZero[i + 1];             if (s[i] == '0')                 suffixCountZero[i]++;         }          // Loop to find the minimum cost         for (int i = 0; i <= count0; i++) {             int x;             if (i == 0) {                 x = count0 - suffixCountZero[n - count0];             }             else if (i == count0) {                 x = count0 - prefixCountZero[count0 - 1];             }             else {                 x = count0 - prefixCountZero[i - 1]                     - suffixCountZero[n - (count0 - i)];             }             ans = Math.Min(ans, x);         }         return ans;     }      // Driver Code     static public void Main()     {         String S = "101110110";          // Function call         Console.WriteLine(minCost(S));     } }  // This code is contributed by Rohit Pradhan 
JavaScript
        // JavaScript code for the above approach          // Function to find the minimum cost         function minCost(s) {             let n = s.length;             let count0 = 0;             let ans = Number.MAX_VALUE;             for (let i = 0; i < n; i++) {                 if (s[i] == '0')                     count0++;             }             let prefixCountZero = new Array(n).fill(0);             let suffixCountZero = new Array(n).fill(0);              // Loop to find the prefix count of 0             for (let i = 0; i < n; i++) {                 if (i != 0)                     prefixCountZero[i] = prefixCountZero[i - 1];                 if (s[i] == '0')                     prefixCountZero[i]++;             }              // Loop to find the suffix count of 0             for (let i = n - 1; i >= 0; i--) {                 if (i != n - 1)                     suffixCountZero[i] = suffixCountZero[i + 1];                 if (s[i] == '0')                     suffixCountZero[i]++;             }              // Loop to find the minimum cost             for (let i = 0; i <= count0; i++) {                 let x;                 if (i == 0) {                     x = count0 - suffixCountZero[n - count0];                 }                 else if (i == count0) {                     x = count0 - prefixCountZero[count0 - 1];                 }                 else {                     x = count0 - prefixCountZero[i - 1]                         - suffixCountZero[n - (count0 - i)];                 }                 ans = Math.min(ans, x);             }             return ans;         }          // Driver code         let S = "101110110";          // Function call         console.log(minCost(S));   // This code is contributed by Potta Lokesh 

Output
1

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Deletions of "01" or "10" in binary string to make it free from "01" or "10"

R

rahulkumar020702
Improve
Article Tags :
  • Strings
  • Greedy
  • Mathematical
  • DSA
Practice Tags :
  • Greedy
  • Mathematical
  • Strings

Similar Reads

  • Minimize removal from front or end to make the Binary String at equilibrium
    Given a binary string S of size N, the task is to find the minimum number of removal required either from the start or end position from the binary strings such that the count of '0' and '1' becomes equal in the final string after removal. Examples: Input: S = "0111010"Output: 3Explanation: Remove 3
    8 min read
  • Find the maximum possible Binary Number from given string
    Given string str consisting of the characters from the set {'o', 'n', 'e', 'z', 'r'}, the task is to find the largest possible binary number that can be formed by rearranging the characters of the given string. Note that the string will form at least a valid number.Examples: Input: str = "roenenzooe
    5 min read
  • Deletions of "01" or "10" in binary string to make it free from "01" or "10"
    Given a binary string str, the task is to find the count of deletion of the sub-string "01" or "10" from the string so that the given string is free from these sub-strings. Print the minimum number of deletions.Examples: Input: str = "11010" Output: 2 The resultant string will be "1"Input: str = "10
    4 min read
  • Maximize count of strings of length 3 that can be formed from N 1s and M 0s
    Given two numbers N and M which denotes the count of ones and zeros respectively, the task is to maximize the count of binary strings of length 3, consisting of both 0 and 1 in them, that can be formed from the given N 1s and M 0s.Examples: Input: N = 4, M = 5 Output: 3 Explanation: Possible strings
    8 min read
  • Minimize deletions in a Binary String to remove all subsequences of the form "0101"
    Given a binary string S of length N, the task is to find the minimum number of characters required to be deleted from the string such that no subsequence of the form “0101” exists in the string. Examples: Input: S = "0101101"Output: 2Explanation: Removing S[1] and S[5] modifies the string to 00111.
    6 min read
  • Find the minimum number of distinct Substrings formed by 0s in Binary String
    Given two integers N and M, the task is to output the minimum number of different substrings that can be formed using the Binary String of length N having M number of set bits. Note: Two substrings let say S[x, y] and S[a, b] are different. If either x != a or y != b. Examples: Input: N = 3, M = 1Ou
    6 min read
  • Find an N-length Binary String having maximum sum of elements from given ranges
    Given an array of pairs ranges[] of size M and an integer N, the task is to find a binary string of length N such that the sum of elements of the string from the given ranges is maximum possible. Examples: Input: N = 5, M = 3, ranges[] = {{1, 3}, {2, 4}, {2, 5}}Output: 01100Explanation:Range [1, 3]:
    5 min read
  • Remove one bit from a binary number to get maximum value
    Given a binary number, the task is to remove exactly one bit from it such that, after it's removal, the resultant binary number is greatest from all the options.Examples: Input: 110 Output: 11 As 110 = 6 in decimal, the option is to remove either 0 or 1. So the possible combinations are 10, 11 The m
    4 min read
  • Maximize the Binary String value by replacing A[i]th elements from start or end
    Given a string S of size M consisting of only zeroes (and hence representing the integer 0). Also, given an array A[] of size N whose, each element is an integer in the range [1, M]. The task is to maximize the integer represented by the string by performing the following operation N times : In ith
    6 min read
  • Minimize cost of flipping or swaps to make a Binary String balanced
    Given a binary string S of size N(where N is even), the task is to find the minimum cost of making the given binary string balanced by flipping one of the adjacent different characters at the cost of 1 unit or swap the characters at indices i and j such that (i < j) at the cost of (j - i) unit. I
    6 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