Increase the count of given subsequences by optimizing the Array
Last Updated :
27 Jul, 2025
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();
Time Complexity: O(N*LogN), As Sorting is performed.
Auxiliary Space: O(N), As ArrayLists are used.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem