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;
// 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
Count subsequence of length three in a given string
Given a string of length n and a subsequence of length 3. Find the total number of occurrences of the subsequence in this string. Examples : Input : string = "GFGFGYSYIOIWIN", subsequence = "GFG" Output : 4 Explanation : There are 4 such subsequences as shown: GFGFGYSYIOIWIN GFGFGYSYIOIWIN GFGFGYSYI
15 min read
Count the strings that are subsequence of the given string
Given a string S and an array arr[] of words, the task is to return the number of words from the array which is a subsequence of S. Examples: Input: S = âprogrammingâ, arr[] = {"prom", "amin", "proj"}Output: 2Explanation: "prom" and "amin" are subsequence of S while "proj" is not) Input: S = âgeeksf
11 min read
Maximize count of Decreasing Subsequences from the given Array
Given an array arr[], the task is to rearrange the array to generate maximum decreasing subsequences and print the count of the maximum number of subsequences possible such that each array element can be part of a single subsequence and the length of the subsequences needs to be maximized. Example:
5 min read
Count of subsequences having odd Bitwise AND values in the given array
Given an array arr[] of N integers, the task is to find the number of subsequences of the given array such that their Bitwise AND value is Odd. Examples: Input: arr[] = {2, 3, 1}Output: 3Explanation: The subsequences of the given array having odd Bitwise AND values are {3} = 3, {1} = 1, {3, 1} = 3
5 min read
Count subsequences of Array having single digit integer sum K
Given an array arr[] and integer K, the task is to count the number of subsequences of the array such that after adding all the elements of that subsequences their single digit integer sum is exactly K. Note: Single digit integer sum is obtained by replacing a number with its digit sum until the num
8 min read
Count of unique Subsequences of given String with lengths in range [0, N]
Given a string S of length N, the task is to find the number of unique subsequences of the string for each length from 0 to N. Note: The uppercase letters and lowercase letters are considered different and the result may be large so print it modulo 1000000007. Examples: Input: S = "ababd"Output: Num
14 min read
Count of Subsequences of given string X in between strings Y and Z
Given three strings, 'X', 'Y' and 'Z', the task is to count the number of subsequences of 'X' which is lexicographically greater than or equal to 'Y' and lexicographically lesser than or equal to 'Z'. Examples: Input: X = "abc", Y = "a", Z = "bc"Output: 6Explanation: The subsequences of X which are
15+ min read
Number of subsequences of an array with given function value
Given an array A[] of length N and integer F, the task is to find the number of subsequences where the average of the sum of the square of elements (of that particular subsequence) is equal to the value F. Examples: Input: A[] = {1, 2, 1, 2}, F = 2Output: 2Explanation: Two subsets with value F = 2 a
12 min read
Count Subsequences with ordered integers in Array
Given an array nums[] of N positive integers, the task is to find the number of subsequences that can be created from the array where each subsequence contains all integers from 1 to its size in any order. If two subsequences have different chosen indices, then they are considered different. Example
7 min read
Count of subsequences in an array with sum less than or equal to X
Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array. Examples: Input : arr[] = {84, 87, 73}, X = 100
13 min read