Given a binary string S and an array arr[] every of measurement N, we will choose any ingredient from the Array which is to the left of (or on the similar place) the indices of ‘1’s within the given binary string. The duty is to search out the utmost potential sum.
Examples:
Enter: arr[] = {20, 10, 30, 9, 20, 9}, string S = “011011”, N = 6
Output: 80
Rationalization: Choose 20, 10, 30 and 20 in Sum, so, Sum = 80.Enter: arr[] = {30, 20, 10}, string S = “000”, N = 3.
Output: 0
Strategy: The given downside could be solved through the use of a precedence queue based mostly on the next thought:
Say there are Okay occurrences of ‘1’ in string S. It may be seen that we will prepare the characters in a means such that we will choose the Okay most parts from the array that are to the left of the final prevalence of ‘1’ in S. So we will use a precedence queue to get these Okay most parts.
Observe the steps to resolve this downside:
- Initialize variable Sum = 0, Cnt = 0.
- Create a precedence queue (max heap) and traverse from i = 0 to N-1:
- If S[i] is ‘1’, increment Cnt by 1.
- Else, whereas Cnt > 0, add the topmost ingredient of the precedence queue and decrement Cnt by 1.
- Push the ith ingredient of the array into the precedence queue.
- After executing the loop, whereas Cnt > 0, add the topmost ingredient of the precedence queue and decrement Cnt by 1.
- Ultimately, return the Sum because the required reply.
Beneath is the implementation of the above strategy.
C++
|
Time Complexity: O(N * log N)
Auxiliary Area: O(N)