Sunday, August 28, 2022
HomeWordPress DevelopmentReduce max frequency distinction of 0 & 1 by dividing Binary String...

Reduce max frequency distinction of 0 & 1 by dividing Binary String into Ok disjoint Subsequence


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given a binary string S of measurement N and an integer Ok, the duty is to divide S into Ok disjoint subsequences(empty subsequences are additionally allowed) such that the utmost absolute distinction between the variety of 0s and 1s amongst these subsequences is minimized.

Instance:

Enter: N = 7, Ok = 5, S = “1010100”
Output: 1
Clarification: Suppose the partition is {“10”, “10”, “0”, “10”, ” “}. 
The respective absolute distinction between 
variety of ones and zeroes are {0, 0, 1, 0, 0}.
The utmost of which is 1.

Enter: N = 6, Ok = 2, S = “101111”
Output: 2

Strategy: The issue might be solved utilizing the beneath mathematical concept:

Discover absolutely the distinction between variety of zeroes and ones current within the binary string, divide it in Ok components by taking worth of ceil(distinction/Ok)

Comply with the steps to implement this concept:

  • Initialize variables ones and zeros each to 0.
  • Iterate over the string and enhance the rely of ones and zeros in line with the characters of the string.
  • Discover absolutely the distinction between ones and zeros and retailer it in variable diff.
  • Return ceil(diff/Ok).

Under is the implementation of this strategy:

Java

  

class GFG {

  

    

    

    public static int minAbsDiff(String S,

                                 int N, int Ok)

    {

        int zeros = 0, ones = 0;

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

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

                ++zeros;

            else

                ++ones;

        }

        double diff = Math.abs(ones - zeros);

        int ans = (int)Math.ceil(diff / Ok);

        return ans;

    }

  

    

    public static void most important(String[] args)

    {

        int N = 7;

        int Ok = 5;

        String S = "1010100";

  

        

        int ans = minAbsDiff(S, N, Ok);

        System.out.println(ans);

    }

}

Time Complexity: O(N)
Auxiliary Area: O(1)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments