Maximize sum by picking Array element to left of each ‘1’ of a Binary String


In this problem, we will find the maximum sum of array elements by picking up unselected elements at the left from the current 1's index.

We can use the vector list and sort() method to solve the problem or priority queue. The priority queue inserts the element in the sorted order.

Problem Statement

We have given a binary string alpha and arr[] of the same length. We need to pick all '1' of alpha one by one and take the maximum element which is not picked from the subarray of arr[] formed using 0 to p elements. Here, P is the index of selected '1' in the binary string. We need to print the maximum sum of such array elements.

Sample Example

Input

alpha = "01010"; arr[] = {30, 40, 3, 7, 20};

Output

70

Explanation

  • For '1' at 1st index, we can pick 40.

  • For '1' at 3rd index, we can pick 30.

So the sum of 40 and 30 is 70.

Input

alpha = "00000"; arr[] = {30, 40, 3, 7, 20};

Output

0

Explanation − The binary string contains all 0. So, it prints the 0 sum.

Input

alpha = "00001"; arr[] = {100, 70, 80, 8, 20};

Output

100

Explanation - We pick the 100 for '1' as it is inside the o to 4 subarray and haven't picked up.

Approach 1

In this approach, we will keep counting 1's and push array elements to the list. Also, we keep sorting the list, and whenever we find the '0' in the binary string, we add the last count number of elements to the sum and remove them from the sorted array. Here, the count is the number of 1's that occurred between the last zero and the current zero.

Algorithm

  • Step 1 − Initialize the 'count' and 'array_sum' with zero to store the count of 1's between two 0's and maximum sum output.

  • Step 2 − Also, define the 'numbers' list to store the array elements.

  • Step 3 − Start traversing the string. If current character in the binary string is '1', increment 'count' by 1.

  • Step 4 − Else, use the hwile loop to make iterations until 'count' is not equal to 0. In the loop, add the last element to the 'array_sum', remove it from the list, and decrement the 'count' by 1.

  • Step 5 − Push current element to the list.

  • Step 6 − Use the sort() method to sort the list.

  • Step 7 − Use the while loop to make iterations until count is not equal to zero. In the loop, add last elemement of the array to array_sum, and remove last element form the list.

  • Step 8 − Return the value of the array_sum.

Example

#include <stdio.h>
#include <stdlib.h>

int getMaximumSum(int arr[], char alpha[], int len) {
   int count = 0, array_sum = 0;
   int numbers[len];
   int numbers_size = 0;

   // Iterate the string
   for (int p = 0; p < len; p++) {
      if (alpha[p] == '1') {
         count++;
      } else {
         // Pop all count number of elements from the stack
         while (count != 0) {
            array_sum += numbers[--numbers_size];
            count--;
         }
      }
      // Push element to stack
      numbers[numbers_size++] = arr[p];
      // Sort the stack (use any sorting algorithm)
      // Example: Bubble Sort
      for (int i = 0; i < numbers_size - 1; i++) {
         for (int j = 0; j < numbers_size - i - 1; j++) {
            if (numbers[j] > numbers[j + 1]) {
               // Swap numbers[j] and numbers[j+1]
               int temp = numbers[j];
               numbers[j] = numbers[j + 1];
               numbers[j + 1] = temp;
            }
         }
      }
   }
   // If the stack is not empty, then pop the elements and do its sum
   while (count != 0) {
      array_sum += numbers[--numbers_size];
      count--;
   }
   // Return the answer
   return array_sum;
}

int main() {
   int len = 5;
   char alpha[] = "01010";
   int arr[] = {30, 40, 3, 7, 20};
   printf("The maximum sum of array elements according to the given condition is %d\n", getMaximumSum(arr, alpha, len));
   return 0;
}

Output

The maximum sum of array elements according to the given condition is 70
#include <bits/stdc++.h>
using namespace std;

int getMaximumSum(int *arr, string alpha, int len) {
   int count = 0, array_sum = 0;
   vector<int> numbers;
   // Iterate the string
   for (int p = 0; p < len; p++) {
      if (alpha[p] == '1') {
         count++;
      } else {
         // Pop all count number of elements from the queue
         while (count != 0) {
            array_sum += numbers[numbers.size() - 1];
            numbers.pop_back();
            count--;
         }
      }
      // Insert element to list
      numbers.push_back(arr[p]);
      // sort the list
      sort(numbers.begin(), numbers.end());
   }
   // If the queue is not empty, then pop the elements and do its sum
   while (count != 0) {
      array_sum += numbers[numbers.size() - 1];
      numbers.pop_back();
      count--;
   }
   // return answer
   return array_sum;
}
int main() {
   int len = 5;
   string alpha = "01010";
   int arr[] = {30, 40, 3, 7, 20};
   cout << "The maximum sum of array elements according to the given condition is " << getMaximumSum(arr, alpha, len) << endl;
   return 0;
}

Output

The maximum sum of array elements according to the given condition is 70
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
   public static int getMaximumSum(int[] arr, String alpha, int len) {
      int count = 0;
      int array_sum = 0;
      List<Integer> numbers = new ArrayList<>();

      // Iterate the string
      for (int p = 0; p < len; p++) {
         if (alpha.charAt(p) == '1') {
            count++;
         } else {
            // Pop all count number of elements from the list
            while (count != 0) {
               array_sum += numbers.get(numbers.size() - 1);
               numbers.remove(numbers.size() - 1);
               count--;
            }
         }
         // Append element to list
         numbers.add(arr[p]);
         // Sort the list
         Collections.sort(numbers);
      }
      // If the list is not empty, then pop the elements and do its sum
      while (count != 0) {
         array_sum += numbers.get(numbers.size() - 1);
         numbers.remove(numbers.size() - 1);
         count--;
      }
      // Return the answer
      return array_sum;
   }

   public static void main(String[] args) {
      int len = 5;
      String alpha = "01010";
      int[] arr = {30, 40, 3, 7, 20};
      System.out.println("The maximum sum of array elements according to the given condition is " + getMaximumSum(arr, alpha, len));
   }
}

Output

The maximum sum of array elements according to the given condition is 70
def getMaximumSum(arr, alpha, len):
   count = 0
   array_sum = 0
   numbers = []

   # Iterate the string
   for p in range(len):
      if alpha[p] == '1':
         count += 1
      else:
         # Pop all count number of elements from the list
         while count != 0:
            array_sum += numbers.pop()
            count -= 1

      # Append element to list
      numbers.append(arr[p])
      # Sort the list
      numbers.sort()

   # If the list is not empty, then pop the elements and do its sum
   while count != 0:
      array_sum += numbers.pop()
      count -= 1

   # Return the answer
   return array_sum

if __name__ == "__main__":
   len = 5
   alpha = "01010"
   arr = [30, 40, 3, 7, 20]
   print("The maximum sum of array elements according to the given condition is", getMaximumSum(arr, alpha, len))

Output

The maximum sum of array elements according to the given condition is 70

Time complexity − O(N*NlogN), where O(N) for traversing the string, and O(NlogN) for sorting the array.

Space complexity − O(N) to store array elements in the list.

Approach 2

In this approach, we will use the priority queue to keep list of elements sorted. It is similar to heap data structure, and insertion is very efficient in the heap.

We can insert the element, and it sets the position of element in the sorted order. When we find '0' in the binary string, we can pop elmenets from the start.

Algorithm

  • Step 1 − Initialize the 'count' and 'array_sum' with 0.

  • Step 2 − Start traversing the binary string. If current character is '1', increment the 'count' by 1.

  • Step 3 − If current character is '0', use the loop to remove the count number of elements from the queue and add to the 'array_sum' variable.

  • Step 4 − Push current element to the queue.

  • Step 5 − If count is not zero, remove count number of elements from the queue.

  • Step 6 − Return the 'array_sum' value.

Example

#include <stdio.h>

void swap(int *a, int *b) {
   int temp = *a;
   *a = *b;
   *b = temp;
}

void heapify(int arr[], int n, int i) {
   int largest = i;
   int left = 2 * i + 1;
   int right = 2 * i + 2;

   if (left < n && arr[left] > arr[largest]) {
      largest = left;
   }

   if (right < n && arr[right] > arr[largest]) {
      largest = right;
   }

   if (largest != i) {
      swap(&arr[i], &arr[largest]);
      heapify(arr, n, largest);
   }
}

void buildMaxHeap(int arr[], int n) {
   for (int i = n / 2 - 1; i >= 0; i--) {
      heapify(arr, n, i);
   }
}

int getMaximumSum(int arr[], char alpha[], int len) {
   int count = 0, array_sum = 0;

   // Build a max heap
   buildMaxHeap(arr, len);

   // Iterate the string
   for (int p = 0; p < len; p++) {
      if (alpha[p] == '1') {
         count++;
      } else {
         // Pop all count number of elements from the heap
         for (int i = 0; i < count; i++) {
            array_sum += arr[0];
            arr[0] = arr[len - 1 - i];
            heapify(arr, len - i, 0);
         }
         count = 0;
      }
   }

   // If there are remaining elements in the heap, pop and sum them
   for (int i = 0; i < count; i++) {
      array_sum += arr[0];
      arr[0] = arr[len - 1 - i];
      heapify(arr, len - i, 0);
   }

   // Return the answer
   return array_sum;
}

int main() {
   int len = 5;
   char alpha[] = "01010";
   int arr[] = {30, 40, 3, 7, 20};

   printf("The maximum sum of array elements according to the given condition is %d\n", getMaximumSum(arr, alpha, len));

   return 0;
}

Output

The maximum sum of array elements according to the given condition is 70
#include <bits/stdc++.h>
using namespace std;

int getMaximumSum(int *arr, string alpha, int len) {
   int count = 0, array_sum = 0;
   priority_queue<int> queue;
   // Iterate the string
   for (int p = 0; p < len; p++) {
      if (alpha[p] == '1') {
         count++;
      } else {
         // Pop all count number of elements from the queue
         while (count != 0) {
            array_sum += queue.top();
            queue.pop();
            count--;
         }
      }
      // Insert element to queue
      queue.push(arr[p]);
   }
   // If the queue is not empty, then pop the elements and do its sum
   while (count != 0) {
      array_sum += queue.top();
      queue.pop();
      count--;
   }
   // return answer
   return array_sum;
}
int main() {
   int len = 5;
   string alpha = "01010";
   int arr[] = {30, 40, 3, 7, 20};
   cout << "The maximum sum of array elements according to the given condition is " << getMaximumSum(arr, alpha, len) << endl;
   return 0;
}

Output

The maximum sum of array elements according to the given condition is 70
import java.util.PriorityQueue;

public class Main {
   public static int getMaximumSum(int[] arr, String alpha) {
      int count = 0;
      int array_sum = 0;
      PriorityQueue<Integer> queue = new PriorityQueue<Integer>((a, b) -> b - a); // Max heap to simulate the queue

      // Iterate the string
      for (int p = 0; p < alpha.length(); p++) {
         if (alpha.charAt(p) == '1') {
            count++;
         } else {
            // Pop all count number of elements from the queue
            while (count != 0) {
               array_sum += queue.poll();
               count--;
            }
         }
         // Insert element into the queue
         queue.offer(arr[p]);
      }

      // If the queue is not empty, then pop the elements and do its sum
      while (count != 0) {
         array_sum += queue.poll();
         count--;
      }

      return array_sum;
   }

   public static void main(String[] args) {
      int len = 5;
      String alpha = "01010";
      int[] arr = {30, 40, 3, 7, 20};
      System.out.println("The maximum sum of array elements according to the given condition is " + getMaximumSum(arr, alpha));
   }
}

Output

The maximum sum of array elements according to the given condition is 70
def get_maximum_sum(arr, alpha):
   count = 0
   array_sum = 0
   queue = []  # List to simulate the queue

   # Iterate the string
   for i in range(len(alpha)):
      if alpha[i] == '1':
         count += 1
      else:
         # Pop all count number of elements from the queue
         while count != 0:
            array_sum += queue.pop(0)
            count -= 1
      # Insert element into the queue
      queue.append(arr[i])

   # If the queue is not empty, then pop the elements and do its sum
   while count != 0:
      array_sum += queue.pop(0)
      count -= 1

   return array_sum

if __name__ == "__main__":
   length = 5  # Changed the variable name from "len" to "length"
   alpha = "01010"
   arr = [30, 40, 3, 7, 20]
   print("The maximum sum of array elements according to the given condition is", get_maximum_sum(arr, alpha))

Output

The maximum sum of array elements according to the given condition is 70

Time complexity − O(N*logN), where O(N) for traversing the string, and O(logN) is for inserting the elment in the queue.

Space complexity − O(N), for storing the element in the queue.

Here, we used the list and queue to solve the problme. We can observe that how queue is efficient. If we need to sort the array after each iteration, we can use the priority queue.

Updated on: 23-Oct-2023

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements