Thursday, October 27, 2022
HomeWordPress DevelopmentReduce the utmost of 0s left or 1s deleted from Binary String

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


  

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 primary(String[] args)

    {

        String S = "101110110";

  

        

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

    }

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments