Given a binary string S, the duty is to search out the longest subsequence with that has equal variety of 0s and 1s and all of the 0s are current earlier than all of the 1s.
Examples:
Enter: S = “0011001111”
Output: 8
Rationalization: By eradicating the third and 4th characters, the string turns into 00001111.
That is the longest potential subsequence following the given circumstances.Enter: S = “11001”
Output: 2
Rationalization: The longest potential subsequence satisfying the circumstances is “01”Enter: S = “111100”
Output: 0
Rationalization: There isn’t any such subsequence that satisfies the circumstances.
Method: The issue might be solved primarily based on the next thought:
For every index, we have to choose the utmost variety of 0s from the beginning and the utmost variety of 1s from the rear finish. This can maximize the size of the required subsequence.
Based mostly on the above thought, we have to do the next:
- For every index, calculate the whole variety of 0s from the beginning and the whole variety of 1s from the tip.
- If the 1s start from ith index then the whole size of the subsequence can be = 2 * min(0s from begin until i, 1s from finish until i).
- The utmost of this for all indices is the reply.
Observe the steps talked about under to implement the thought:
- Construct two arrays (say pre[] and publish[]) to retailer the rely of 0s from the beginning and the rely of 1s from the tip.
- Iterate from i = 0 to N-1:
- If S[i] is 0, increment the rely of 0s and retailer it in pre[i].
- Iterate from i = N-1 to 0:
- If S[i] is 1, increment the rely 1s from finish and retailer it in publish[i].
- Iterate the arrays from i = 0 to N-1:
- Calculate the size of the subsequence if this index is the breaking level between 1s and 0s.
- Most amongst these subsequences is the required size of the subsequence.
Under is the implementation of the above strategy.
C++
|
Time Complexity: O(N) the place N is the size of the String
Auxiliary House: O(N)