Open In App

Generate Lexicographically Largest Array through Even Swaps

Given an array a[] and you need to generate an array b[]. You are allowed to apply only one type of operation on the array a[], any number of times. In one operation you can swap ai with ai+1 only if ai+ai+1 is even. Array b[] thus generated by applying the given operation any number of times, should be lexicographically the largest among all arrays that can be generated from array a.

Examples:



Input: N = 3, a[] = {1, 3, 5}
Output: 5, 3, 1
Explanation: [1, 3, 5], [1, 5, 3], [3, 1, 5], [3, 5, 1], [5, 1, 3] and [5, 3, 1] are all possible values of array b while the last one is lexicographically largest.

Input: N = 4, a[] = {1, 3, 4, 2}
Output: b[] = {3, 1, 4, 2}
Explanation: [1, 3, 4, 2], [1, 3, 2, 4], [3, 1, 2, 4] and [3, 1, 4, 2] are all possible values of b among which the last one is lexicographically largest one.



Approach: To solve the problem follow the below observations:

Observations:

  • Basically separating segments on the basis of same parity and as in same parity segments we can do any number of swaps so sorting it in decreasing order will give us the lexicographically largest array.
  • Also we know that the summation of two even numbers i.e. even +even=even and odd+even=odd so this will give us two separate segments and odd+ odd =even so these numbers will be in same segments. that’s why we are separating the segments on the basis of same parity.

Step-by-step approach:

Below is the implementation of the above approach:




#include <algorithm>
#include <iostream>
#include <vector>
 
using namespace std;
 
// Function to find the lexicographically
// largest array.
vector<int> lexicographicallyLargest(vector<int>& a, int n)
{
    int i = 0;
    // Iterating through the array.
    while (i < n) {
        int j = i + 1;
        // Checking if the current number and
        // the next number have the same parity.
        while (j < n && a[j] % 2 == a[j - 1] % 2) {
            j++;
        }
 
        // Sorting the subarray in
        // descending order.
        sort(a.begin() + i, a.begin() + j, greater<int>());
        i = j;
    }
 
    // Returning the lexicographically
    // largest array.
    return a;
}
 
// Drivers code
int main()
{
 
    int n = 3;
    vector<int> a = { 1, 3, 5 };
 
    vector<int> result = lexicographicallyLargest(a, n);
 
    // Function Call
    cout << "Lexicographically Largest Array: ";
    for (int i = 0; i < n; i++) {
        cout << result[i] << " ";
    }
    cout << endl;
 
    return 0;
}




import java.util.ArrayList;
import java.util.Collections;
 
public class LexicographicallyLargest {
 
    // Function to find the lexicographically
    // largest array.
    static ArrayList<Integer>
    lexicographicallyLargest(ArrayList<Integer> a, int n)
    {
        int i = 0;
        // Iterating through the array.
        while (i < n) {
            int j = i + 1;
            // Checking if the current number and
            // the next number have the same parity.
            while (j < n
                   && a.get(j) % 2 == a.get(j - 1) % 2) {
                j++;
            }
 
            // Sorting the subarray in
            // descending order.
            Collections.sort(a.subList(i, j),
                             Collections.reverseOrder());
            i = j;
        }
 
        // Returning the lexicographically
        // largest array.
        return a;
    }
 
    // Drivers code
    public static void main(String[] args)
    {
 
        int n = 3;
        ArrayList<Integer> a = new ArrayList<>();
        a.add(1);
        a.add(3);
        a.add(5);
 
        ArrayList<Integer> result
            = lexicographicallyLargest(a, n);
 
        // Function Call
        System.out.print(
            "Lexicographically Largest Array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(result.get(i) + " ");
        }
        System.out.println();
    }
}




# Function to find the lexicographically
# largest array.
def lexicographically_largest(a, n):
    i = 0
    # Iterating through the array.
    while i < n:
        j = i + 1
        # Checking if the current number and
        # the next number have the same parity.
        while j < n and a[j] % 2 == a[j - 1] % 2:
            j += 1
 
        # Sorting the subarray in
        # descending order.
        a[i:j] = sorted(a[i:j], reverse=True)
        i = j
 
    # Returning the lexicographically
    # largest array.
    return a
 
# Driver code
if __name__ == "__main__":
    n = 3
    a = [1, 3, 5]
 
    result = lexicographically_largest(a, n)
 
    # Function Call
    print("Lexicographically Largest Array:", end=" ")
    for i in range(n):
        print(result[i], end=" ")
    print()




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Function to find the lexicographically
    // largest array.
    static List<int> LexicographicallyLargest(List<int> a, int n)
    {
        int i = 0;
        // Iterating through the array.
        while (i < n)
        {
            int j = i + 1;
            // Checking if the current number and
            // the next number have the same parity.
            while (j < n && a[j] % 2 == a[j - 1] % 2)
            {
                j++;
            }
 
            // Sorting the subarray in
            // descending order.
            a.Sort(i, j - i, Comparer<int>.Create((x, y) => y.CompareTo(x)));
            i = j;
        }
 
        // Returning the lexicographically
        // largest array.
        return a;
    }
 
    // Drivers code
    static void Main()
    {
        int n = 3;
        List<int> a = new List<int> { 1, 3, 5 };
 
        List<int> result = LexicographicallyLargest(a, n);
 
        // Function Call
        Console.Write("Lexicographically Largest Array: ");
        for (int i = 0; i < n; i++)
        {
            Console.Write(result[i] + " ");
        }
        Console.WriteLine();
 
        // Pause execution to see the result
        Console.ReadLine();
    }
}




// Function to find the lexicographically largest array.
function lexicographicallyLargest(a, n) {
    let i = 0;
 
    // Iterating through the array.
    while (i < n) {
        let j = i + 1;
 
        // Checking if the current number and the next number have the same parity.
        while (j < n && a[j] % 2 === a[j - 1] % 2) {
            j++;
        }
 
        // Sorting the subarray in descending order.
        a = a.slice(0, i).concat(a.slice(i, j).sort((x, y) => y - x), a.slice(j));
 
        i = j;
    }
 
    // Returning the lexicographically largest array.
    return a;
}
 
// Main function
function main() {
    const n = 3;
    const a = [1, 3, 5];
 
    const result = lexicographicallyLargest(a, n);
 
    // Function Call
    console.log("Lexicographically Largest Array: " + result.join(' '));
}
 
// Invoke the main function
main();
 
// This code is contributed by shivamgupta310570

Output
Lexicographically Largest Array: 5 3 1 












Time complexity: O(NlogN) logN for sorting the array (subsegments)
Auxiliary Space : O(1) as we are using no space .


Article Tags :