Maximize sum by picking Array element to left of each '1' of a Binary String
Last Updated :
15 Nov, 2022
Given a binary string S and an array arr[] each of size N, we can pick any element from the Array which is to the left of (or at the same position) the indices of '1's in the given binary string. The task is to find the maximum possible sum.
Examples:
Input: arr[] = {20, 10, 30, 9, 20, 9}, string S = "011011", N = 6
Output: 80
Explanation: Pick 20, 10, 30 and 20 in Sum, so, Sum = 80.
Input: arr[] = {30, 20, 10}, string S = "000", N = 3.
Output: 0
Approach: The given problem can be solved by using a priority queue based on the following idea:
Say there are K occurrences of '1' in string S. It can be seen that we can arrange the characters in a way such that we can pick the K maximum elements from the array which are to the left of the last occurrence of '1' in S. So we can use a priority queue to get these K maximum elements.
Follow the steps to solve this problem:
- Initialize variable Sum = 0, Cnt = 0.
- Create a priority queue (max heap) and traverse from i = 0 to N-1:
- If S[i] is '1', increment Cnt by 1.
- Else, while Cnt > 0, add the topmost element of the priority queue and decrement Cnt by 1.
- Push the ith element of the array into the priority queue.
- After executing the loop, while Cnt > 0, add the topmost element of the priority queue and decrement Cnt by 1.
- At last, return the Sum as the required answer.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find maximum Sum
int findMaxSum(int* arr, string s, int n)
{
// Initialize variables
int Cnt = 0, Sum = 0;
priority_queue<int> pq;
// Traverse the string
for (int i = 0; i < n; i++) {
if (s[i] == '1') {
Cnt++;
}
else {
while (Cnt != 0) {
Sum += pq.top();
pq.pop();
Cnt--;
}
}
// Push the element of array in pq
pq.push(arr[i]);
}
while (Cnt != 0) {
Sum += pq.top();
pq.pop();
Cnt--;
}
// Return Max Sum
return Sum;
}
// Driver Code
int main()
{
int N = 6;
string S = "011011";
int arr[] = { 20, 10, 30, 9, 20, 9 };
// Function Call
cout << findMaxSum(arr, S, N) << endl;
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
public class GFG
{
// Function to find maximum Sum
static int findMaxSum(int[] arr, String s, int n)
{
// Initialize variables
int Cnt = 0, Sum = 0;
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>(
Collections.reverseOrder());
// Traverse the string
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '1') {
Cnt++;
}
else {
while (Cnt != 0) {
Sum += pq.peek();
pq.poll();
Cnt--;
}
}
// Push the element of array in pq
pq.add(arr[i]);
}
while (Cnt != 0) {
Sum += pq.peek();
pq.poll();
Cnt--;
}
// Return Max Sum
return Sum;
}
// Driver Code
public static void main(String[] args)
{
int N = 6;
String S = "011011";
int[] arr = { 20, 10, 30, 9, 20, 9 };
// Function Call
System.out.println(findMaxSum(arr, S, N));
return;
}
}
// This code is contributed by garg28harsh.
Python3
# Python code to implement the approach
import heapq
# Function to find maximum Sum
def findMaxSum(arr, s, n):
# Initialize variables
Cnt, Sum = 0, 0
pq = []
heapq._heapify_max(pq)
# Traverse the string
for i in range(n):
if(s[i] == '1'):
Cnt += 1
else:
while(Cnt is not 0):
Sum += heapq.heappop(pq)
heapq._heapify_max(pq)
Cnt -= 1
# Push the element of array in pq
heapq.heappush(pq, arr[i])
heapq._heapify_max(pq)
while(Cnt is not 0):
Sum += heapq.heappop(pq)
heapq._heapify_max(pq)
Cnt -= 1
# Return Max Sum
return Sum
N = 6
S = "011011"
arr = [20, 10, 30, 9, 20, 9]
# Function call
print(findMaxSum(arr, S, N))
# This code is contributed by lokesh
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
// Function to find maximum Sum
static int findMaxSum(int[] arr, string s, int n)
{
// Initialize variables
int Cnt = 0, Sum = 0;
List<int> pq = new List<int>();
// Traverse the string
for (int i = 0; i < n; i++) {
pq.Sort((a, b) => b.CompareTo(a));
if (s[i] == '1') {
Cnt++;
}
else {
while (Cnt != 0) {
pq.Sort((a, b) => b.CompareTo(a));
Sum += pq[0];
pq.RemoveAt(0);
Cnt--;
}
}
// Push the element of array in pq
pq.Add(arr[i]);
}
while (Cnt != 0) {
pq.Sort((a, b) => b.CompareTo(a));
Sum += pq[0];
pq.RemoveAt(0);
Cnt--;
}
// Return Max Sum
return Sum;
}
// Driver Code
public static void Main(string[] args)
{
int N = 6;
string S = "011011";
int[] arr = { 20, 10, 30, 9, 20, 9 };
// Function Call
Console.WriteLine(findMaxSum(arr, S, N));
}
}
// This code is contributed by Tapesh(tapeshdua420)
JavaScript
// Javascript code to implement the approach
// Function to find maximum Sum
function findMaxSum(arr, s, n)
{
// Initialize variables
let Cnt = 0;
let Sum = 0;
pq=[];
// Traverse the string
for (let i = 0; i < n; i++) {
if (s[i] == '1') {
Cnt++;
}
else {
while (Cnt != 0) {
Sum += pq[pq.length-1];
pq.pop();
Cnt--;
}
}
// Push the element of array in pq
pq.push(arr[i]);
pq.sort((a,b)=>a-b);
}
while (Cnt != 0) {
Sum += pq[pq.length-1];
pq.pop();
Cnt--;
}
// Return Max Sum
return Sum;
}
// Driver Code
let N = 6;
let S = "011011";
let arr = [ 20, 10, 30, 9, 20, 9 ];
// Function Call
console.log(findMaxSum(arr, S, N));
// This code is contributed by Pushpesh Raj.
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Similar Reads
Maximize count of 0s in left and 1s in right substring by splitting given Binary string Given a binary string str, the task is to split the given binary string at any index into two non-empty substrings such that the sum of counts of 0s in the left substring and 1s in the right substring is maximum. Print the sum of such 0s and 1s in the end.Examples: Input: str = "0011110011" Output:
6 min read
Maximum number of consecutive 1's in binary representation of all the array elements Given an array arr[] of N elements, the task is to find the maximum number of consecutive 1's in the binary representation of an element among all the elements of the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 2 Binary(1) = 01 Binary(2) = 10 Binary(3) = 11 Binary(4) = 100 Input: arr[
6 min read
Maximize the Binary String value by replacing A[i]th elements from start or end Given a string S of size M consisting of only zeroes (and hence representing the integer 0). Also, given an array A[] of size N whose, each element is an integer in the range [1, M]. The task is to maximize the integer represented by the string by performing the following operation N times : In ith
6 min read
Maximize count of elements reaching the end of an Array Given an array arr[] consisting of N integers, where each element denotes the maximum number of elements that can be placed on that index and an integer X, which denotes the maximum indices that can be jumped from an index, the task is to find the number of elements that can reach the end of the arr
15 min read
Maximize sum by splitting given binary strings based on given conditions Given two binary strings str1 and str2 each of length N, the task is to split the strings in such a way that the sum is maximum with given conditions. Split both strings at the same position into equal length substrings.If both the substrings have only 0's then the value of that substring to be adde
7 min read