Decrease the utmost of 0s left or 1s deleted from Binary String

[ad_1]

  

import java.io.*;

  

class GFG {

  

    

    public static int minCost(String s)

    {

        int n = s.size();

        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];

  

        

        for (int i = 0; i < n; i++) {

            if (i != 0)

                prefixCountZero[i] = prefixCountZero[i - 1];

            if (s.charAt(i) == '0')

                prefixCountZero[i]++;

        }

  

        

        for (int i = n - 1; i >= 0; i--) {

            if (i != n - 1)

                suffixCountZero[i] = suffixCountZero[i + 1];

            if (s.charAt(i) == '0')

                suffixCountZero[i]++;

        }

  

        

        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;

    }

  

    

    public static void essential(String[] args)

    {

        String S = "101110110";

  

        

        System.out.println(minCost(S));

    }

}

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *