Open In App

Increase the count of given subsequences by optimizing the Array

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array X[] of length N. Which contains the alternate frequency of 0s and 1s in Binary String starting from 0. Then the task is to maximize the count of the “01” subsequence where you can choose two different elements of X[], let’s say Xi and Xj such that abs (i – j) = 2, and then swap Xi and Xj.

Examples:

Input: N = 4, X[] = {2, 3, 4, 3)
Output: X[] = {4, 3, 2, 3}, Count of 01 subsequences = 30
Explanation: Take X1 and X3, because abs(1 – 3) = 2 and then swap X1 and X3. Now updated X[] is: {4, 3, 2, 3}, which gives binary string as: 000011100111 contaning 30 occurrences of “01” subsequences. It can ne verified that it is maximum possible count of the “01” subsequences.

Input: N = 5, X[] = {1, 3, 2, 4, 6}
Output: X[] = {6, 3, 2, 4, 1}, Count of 01 subsequences = 50
Explanation: It can be verified that the output X[] is optimized to maximize the required 01 subsequences.

For more clarification of the problem see below and test cases as well:

The String formation from X[] is as follows:

Let say X[] = {2, 1, 3, 4}

Then moving from left to right in X[] we have to construct a binary string. Odd indices in X[] shows number of zeros and even indices shows number of 1s. Then, Binary string made by X[] will be as follows:

((X[1]) 0s) + ((X[2]) 1s) + ((X[3]) 0s) + ((X[4]) 1s) = ((2) 0s) + ((1) 1s) + ((3) 0s) + ((4) 1s) = 0010001111.

You need to optimize X[] using given operation. So that after operation the Binary String formed by X[] have maximum number of 01 subsequences.

Approach: Implement the idea below to solve the problem

The problem can be solved using the concept of Sorting. We have to create two ArrayLists for storing the indices of 0s and 1s and then have to apply sorting on them. The main idea behind sorting the arrays is to maximize the number of ’01’ subsequences in the binary string.

In a binary string, a ’01’ subsequence represents a transition from 0 to 1. To maximize the number of such transitions, we want to distribute the 0’s and 1’s as evenly as possible throughout the string.

  • Significance of Sorting: By sorting the Arrays, we are effectively rearranging the blocks of 0’s and 1’s in the binary string. We sort the array of 0’s in descending order to place the largest blocks of 0’s at the beginning of the string. Similarly, we sort the array of 1’s in ascending order to place the smallest blocks of 1’s after each block of 0’s. This arrangement ensures that we have a transition from 0 to 1 at as many places as possible.

The reason we can’t just sort all elements together is because we can only swap elements that represent blocks of the same character (either 0 or 1). This is why we separate the counts into two different arrays and sort them separately.

After sorting, we merge the arrays by alternately taking an element from each array. This gives us a new arrangement of blocks that maximizes the number of “01” subsequences.

In summary, sorting is used as a tool to rearrange the blocks of 0’s and 1’s in a way that maximizes the number of transitions from 0 to 1, thereby maximizing the number of ’01’ subsequences.

Steps were taken to solve the problem:

  • Initialize two ArrayLists: Create two ArrayLists let say, ZeroCounts and OneCounts, to store the counts of 0’s and 1’s respectively from X[].
  • Separate counts of 0’s and 1’s: Iterate over X[]. For every even-indexed element (starting from index 0), add it to ZeroCounts. For every odd-indexed element (starting from index 1), add it to OneCounts.
  • Sort the ArrayLists: Sort ZeroCounts in descending order and OneCounts in ascending order. This is done using the Collections.sort() inbuilt method in Java. To sort in descending order, we use Collections.reverseOrder() as the comparator.
  • Initialize variables for subsequences and cumulative sum: Initialize two variables let say totalSubsequences and CumulativeZeroCount, to keep track of the total number of “01” subsequences and the cumulative sum of zero counts respectively.
  • Iterate over both lists simultaneously: Iterate over both ZeroCounts and OneCounts simultaneously using a loop. In each iteration, print an element from ZeroCounts and then an element from OneCounts. Also, update CumulativeZeroCount by adding the current element from ZeroCounts, and update TotalSubsequences by adding the product of CumulativeZeroCount and the current element from OneCounts.
  • Handle odd length of X[]: If the original X[] has an odd length, it means it ends with a count of 0’s. In this case, print the last element from ZeroCounts.
  • Print total number of subsequences: Finally, print the value of TotalSubsequences, which represents the total number of ’01’ subsequences in the final binary string.

Implementation of the above approach:

C++




#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
// Method to optimize X[]
void optimizeX(int N, int X[]) {
    // Vectors to store counts of 0's and 1's
    vector<int> zeroCounts;
    vector<int> oneCounts;
 
    // Initialize zeroCounts with counts of 0's from the compression array
    for (int i = 0; i < N; i += 2) {
        zeroCounts.push_back(X[i]);
    }
 
    // Initialize oneCounts with counts of 1's from the compression array
    for (int i = 1; i < N; i += 2) {
        oneCounts.push_back(X[i]);
    }
 
    // Sort zeroCounts in descending order and oneCounts in ascending order
    sort(zeroCounts.begin(), zeroCounts.end(), greater<int>());
    sort(oneCounts.begin(), oneCounts.end());
 
    // Variable to keep track of the total number of '01' subsequences
    int totalSubsequences = 0;
 
    // Variable to keep track of the cumulative sum of zero counts
    int cumulativeZeroCount = 0;
 
    // Iterate over both vectors simultaneously
    for (int i = 0; i < oneCounts.size(); i++) {
        cout << zeroCounts[i] << " ";
        cout << oneCounts[i] << " ";
 
        // Update the cumulative sum of zero counts
        cumulativeZeroCount += zeroCounts[i];
 
        // Update the total number of '01' subsequences
        totalSubsequences += cumulativeZeroCount * oneCounts[i];
    }
 
    // If the original array has an odd length, print the last element from zeroCounts
    if (N % 2 == 1) {
        cout << zeroCounts.back() << " ";
    }
 
    cout << endl;
 
    // Print the total number of '01' subsequences in the final string
    cout << totalSubsequences << endl;
}
 
// Driver Function
int main() {
    // Inputs
    int N = 5;
    int X[] = {1, 3, 2, 4, 6};
 
    // Function call to optimize the X
    optimizeX(N, X);
 
    return 0;
}


Java




// Java code to implement the approach
 
import java.util.*;
 
// Driver Class
class GFG {
 
    // Driver Function
    public static void main(String[] args)
    {
        // Inputs
        int N = 5;
        int X[] = { 1, 3, 2, 4, 6 };
 
        // Function call to optimize the X
        optimizeX(N, X);
    }
 
    // Method to optimize X[]
    public static void optimizeX(int N, int[] X)
    {
        // ArrayLists to store counts of 0's and 1's
        ArrayList<Integer> zeroCounts = new ArrayList<>();
        ArrayList<Integer> oneCounts = new ArrayList<>();
 
        // Initialize zeroCounts with counts of 0's from the
        // compression array
        for (int i = 0; i < N; i += 2) {
            zeroCounts.add(X[i]);
        }
 
        // Initialize oneCounts with counts of 1's from the
        // compression array
        for (int i = 1; i < N; i += 2) {
            oneCounts.add(X[i]);
        }
 
        // Sort zeroCounts in descending order and oneCounts
        // in ascending order
        Collections.sort(zeroCounts,
                         Collections.reverseOrder());
        Collections.sort(oneCounts);
 
        // Variable to keep track of the total number of
        // '01' subsequences
        int totalSubsequences = 0;
 
        // Variable to keep track of the cumulative sum of
        // zero counts
        int cumulativeZeroCount = 0;
 
        // Iterate over both lists simultaneously
        for (int i = 0; i < oneCounts.size(); i++) {
            System.out.print(zeroCounts.get(i) + " ");
            System.out.print(oneCounts.get(i) + " ");
 
            // Update the cumulative sum of zero counts
            cumulativeZeroCount += zeroCounts.get(i);
 
            // Update the total number of '01' subsequences
            totalSubsequences
                += cumulativeZeroCount * oneCounts.get(i);
        }
 
        // If the original array has an odd length, print
        // the last element from zeroCounts
        if (N % 2 == 1) {
            System.out.print(
                zeroCounts.get(zeroCounts.size() - 1)
                + " ");
        }
 
        System.out.println();
 
        // Print the total number of '01' subsequences in
        // the final string
        System.out.println(totalSubsequences);
    }
}


Python3




def optimize_X(N, X):
    # Lists to store counts of 0's and 1's
    zero_counts = []
    one_counts = []
 
    # Initialize zero_counts with counts of 0's from the compression array
    for i in range(0, N, 2):
        zero_counts.append(X[i])
 
    # Initialize one_counts with counts of 1's from the compression array
    for i in range(1, N, 2):
        one_counts.append(X[i])
 
    # Sort zero_counts in descending order and one_counts in ascending order
    zero_counts.sort(reverse=True)
    one_counts.sort()
 
    # Variable to keep track of the total number of '01' subsequences
    total_subsequences = 0
 
    # Variable to keep track of the cumulative sum of zero counts
    cumulative_zero_count = 0
 
    # Iterate over both lists simultaneously
    for i in range(len(one_counts)):
        print(zero_counts[i], end=" ")
        print(one_counts[i], end=" ")
 
        # Update the cumulative sum of zero counts
        cumulative_zero_count += zero_counts[i]
 
        # Update the total number of '01' subsequences
        total_subsequences += cumulative_zero_count * one_counts[i]
 
    # If the original list has an odd length, print the last element from zero_counts
    if N % 2 == 1:
        print(zero_counts[-1], end=" ")
 
    print()
 
    # Print the total number of '01' subsequences in the final string
    print(total_subsequences)
 
# Driver Function
def main():
    # Inputs
    N = 5
    X = [1, 3, 2, 4, 6]
 
    # Function call to optimize the X
    optimize_X(N, X)
 
if __name__ == "__main__":
    main()


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG
{
    static void OptimizeX(int N, int[] X)
    {
        // Lists to store counts of 0's and 1's
        List<int> zeroCounts = new List<int>();
        List<int> oneCounts = new List<int>();
        // Initialize zeroCounts with counts of
      // 0's from the compression array
        for (int i = 0; i < N; i += 2)
        {
            zeroCounts.Add(X[i]);
        }
        // Initialize oneCounts with counts of
      // 1's from the compression array
        for (int i = 1; i < N; i += 2)
        {
            oneCounts.Add(X[i]);
        }
        // Sort zeroCounts in descending order and
      // oneCounts in ascending order
        zeroCounts.Sort((a, b) => b.CompareTo(a));
        oneCounts.Sort();
        int totalSubsequences = 0;
        int cumulativeZeroCount = 0;
        // Iterate over both lists simultaneously
        for (int i = 0; i < oneCounts.Count; i++)
        {
            Console.Write(zeroCounts[i] + " ");
            Console.Write(oneCounts[i] + " ");
            // Update the cumulative sum of the zero counts
            cumulativeZeroCount += zeroCounts[i];
            // Update the total number of '01' subsequences
            totalSubsequences += cumulativeZeroCount * oneCounts[i];
        }
        // If the original array has an odd length
      // print the last element from the zeroCounts
        if (N % 2 == 1)
        {
            Console.Write(zeroCounts.Last() + " ");
        }
        Console.WriteLine();
        // Print the total number of '01' subsequences in final string
        Console.WriteLine(totalSubsequences);
    }
    // Driver Function
    static void Main()
    {
        // Inputs
        int N = 5;
        int[] X = { 1, 3, 2, 4, 6 };
        OptimizeX(N, X);
    }
}


Javascript




// Method to optimize X[]
function optimizeX(N, X) {
    // Arrays to store counts of 0's and 1's
    let zeroCounts = [];
    let oneCounts = [];
 
    // Initialize zeroCounts with counts of 0's from the compression array
    for (let i = 0; i < N; i += 2) {
        zeroCounts.push(X[i]);
    }
 
    // Initialize oneCounts with counts of 1's from the compression array
    for (let i = 1; i < N; i += 2) {
        oneCounts.push(X[i]);
    }
 
    // Sort zeroCounts in descending order and oneCounts in ascending order
    zeroCounts.sort((a, b) => b - a);
    oneCounts.sort((a, b) => a - b);
 
    // Variable to keep track of the total number of '01' subsequences
    let totalSubsequences = 0;
 
    // Variable to keep track of the cumulative sum of zero counts
    let cumulativeZeroCount = 0;
 
    // Iterate over both arrays simultaneously
    for (let i = 0; i < oneCounts.length; i++) {
        console.log(zeroCounts[i], oneCounts[i]);
 
        // Update the cumulative sum of zero counts
        cumulativeZeroCount += zeroCounts[i];
 
        // Update the total number of '01' subsequences
        totalSubsequences += cumulativeZeroCount * oneCounts[i];
    }
 
    // If the original array has an odd length, print the last element from zeroCounts
    if (N % 2 === 1) {
        console.log(zeroCounts[zeroCounts.length - 1]);
    }
 
    console.log();
 
    // Print the total number of '01' subsequences in the final string
    console.log(totalSubsequences);
}
 
// Driver Function
function main() {
    // Inputs
    let N = 5;
    let X = [1, 3, 2, 4, 6];
 
    // Function call to optimize the X
    optimizeX(N, X);
}
 
// Run the main function
main();


Output

6 3 2 4 1 
50








Time Complexity: O(N*LogN), As Sorting is performed.
Auxiliary Space: O(N), As ArrayLists are used.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads