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
|
Time Complexity: O(N)
Auxiliary Area: O(1)