Increase the count of given subsequences by optimizing the Array
Last Updated :
20 Dec, 2023
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;
void optimizeX( int N, int X[]) {
vector< int > zeroCounts;
vector< int > oneCounts;
for ( int i = 0; i < N; i += 2) {
zeroCounts.push_back(X[i]);
}
for ( int i = 1; i < N; i += 2) {
oneCounts.push_back(X[i]);
}
sort(zeroCounts.begin(), zeroCounts.end(), greater< int >());
sort(oneCounts.begin(), oneCounts.end());
int totalSubsequences = 0;
int cumulativeZeroCount = 0;
for ( int i = 0; i < oneCounts.size(); i++) {
cout << zeroCounts[i] << " " ;
cout << oneCounts[i] << " " ;
cumulativeZeroCount += zeroCounts[i];
totalSubsequences += cumulativeZeroCount * oneCounts[i];
}
if (N % 2 == 1) {
cout << zeroCounts.back() << " " ;
}
cout << endl;
cout << totalSubsequences << endl;
}
int main() {
int N = 5;
int X[] = {1, 3, 2, 4, 6};
optimizeX(N, X);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int N = 5 ;
int X[] = { 1 , 3 , 2 , 4 , 6 };
optimizeX(N, X);
}
public static void optimizeX( int N, int [] X)
{
ArrayList<Integer> zeroCounts = new ArrayList<>();
ArrayList<Integer> oneCounts = new ArrayList<>();
for ( int i = 0 ; i < N; i += 2 ) {
zeroCounts.add(X[i]);
}
for ( int i = 1 ; i < N; i += 2 ) {
oneCounts.add(X[i]);
}
Collections.sort(zeroCounts,
Collections.reverseOrder());
Collections.sort(oneCounts);
int totalSubsequences = 0 ;
int cumulativeZeroCount = 0 ;
for ( int i = 0 ; i < oneCounts.size(); i++) {
System.out.print(zeroCounts.get(i) + " ");
System.out.print(oneCounts.get(i) + " ");
cumulativeZeroCount += zeroCounts.get(i);
totalSubsequences
+= cumulativeZeroCount * oneCounts.get(i);
}
if (N % 2 == 1 ) {
System.out.print(
zeroCounts.get(zeroCounts.size() - 1 )
+ " ");
}
System.out.println();
System.out.println(totalSubsequences);
}
}
|
Python3
def optimize_X(N, X):
zero_counts = []
one_counts = []
for i in range ( 0 , N, 2 ):
zero_counts.append(X[i])
for i in range ( 1 , N, 2 ):
one_counts.append(X[i])
zero_counts.sort(reverse = True )
one_counts.sort()
total_subsequences = 0
cumulative_zero_count = 0
for i in range ( len (one_counts)):
print (zero_counts[i], end = " " )
print (one_counts[i], end = " " )
cumulative_zero_count + = zero_counts[i]
total_subsequences + = cumulative_zero_count * one_counts[i]
if N % 2 = = 1 :
print (zero_counts[ - 1 ], end = " " )
print ()
print (total_subsequences)
def main():
N = 5
X = [ 1 , 3 , 2 , 4 , 6 ]
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)
{
List< int > zeroCounts = new List< int >();
List< int > oneCounts = new List< int >();
for ( int i = 0; i < N; i += 2)
{
zeroCounts.Add(X[i]);
}
for ( int i = 1; i < N; i += 2)
{
oneCounts.Add(X[i]);
}
zeroCounts.Sort((a, b) => b.CompareTo(a));
oneCounts.Sort();
int totalSubsequences = 0;
int cumulativeZeroCount = 0;
for ( int i = 0; i < oneCounts.Count; i++)
{
Console.Write(zeroCounts[i] + " " );
Console.Write(oneCounts[i] + " " );
cumulativeZeroCount += zeroCounts[i];
totalSubsequences += cumulativeZeroCount * oneCounts[i];
}
if (N % 2 == 1)
{
Console.Write(zeroCounts.Last() + " " );
}
Console.WriteLine();
Console.WriteLine(totalSubsequences);
}
static void Main()
{
int N = 5;
int [] X = { 1, 3, 2, 4, 6 };
OptimizeX(N, X);
}
}
|
Javascript
function optimizeX(N, X) {
let zeroCounts = [];
let oneCounts = [];
for (let i = 0; i < N; i += 2) {
zeroCounts.push(X[i]);
}
for (let i = 1; i < N; i += 2) {
oneCounts.push(X[i]);
}
zeroCounts.sort((a, b) => b - a);
oneCounts.sort((a, b) => a - b);
let totalSubsequences = 0;
let cumulativeZeroCount = 0;
for (let i = 0; i < oneCounts.length; i++) {
console.log(zeroCounts[i], oneCounts[i]);
cumulativeZeroCount += zeroCounts[i];
totalSubsequences += cumulativeZeroCount * oneCounts[i];
}
if (N % 2 === 1) {
console.log(zeroCounts[zeroCounts.length - 1]);
}
console.log();
console.log(totalSubsequences);
}
function main() {
let N = 5;
let X = [1, 3, 2, 4, 6];
optimizeX(N, X);
}
main();
|
Time Complexity: O(N*LogN), As Sorting is performed.
Auxiliary Space: O(N), As ArrayLists are used.
Share your thoughts in the comments
Please Login to comment...