Open In App

Lexicographically largest Array by swapping adjacent with even sum

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

You are given an array arr[] of size N. You can swap two adjacent elements of the array if their sum is even. The task is to find the lexicographically largest possible array that can be generated by performing this operation any number of times.

Examples:

Input: N = 3, arr[] = {1, 3, 5}
Output: {5, 3, 1}
Explanation: The sequence of operation is [1, 3, 5] -> [1, 5, 3] -> [5, 1, 3] -> [5, 3, 1].

Input: N = 4, arr[] ={ 1, 3, 4, 2}
Output: {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 the final array among which the last one is the lexicographically largest.

Approach: The problem can be solved based on the following idea:

Separate the 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.

Aso we know that the summation of  two even numbers = even, sum of two odd numbers = even and sum of one odd and one even is odd, that’s why we are separating the segments on the basis of same parity.

Follow the steps mentioned to implement the idea:

  • Set starting index of the subsegment as i = 0.
  • Run a loop from i = 0 to N:
    • Find the end of the same parity segment.
    • Sort the segment in decreasing order.
    • Set i to the index just after the end of the segment.
  • Return the final array.

Below is the implementation of the above approach.

C++




#include <bits/stdc++.h>
using namespace std;
vector<int> lexicographicallyLargest(vector<int>& a, int n)
{
    int i = 0;
    while (i < n) {
        int j = i + 1;
        while (j < n && a[j] % 2 == a[j - 1] % 2) {
            j++;
        }
        sort(a.begin() + i, a.begin() + j, greater<int>());
        i = j;
    }
    return a;
}
 
int main()
{
 
    int n = 3;
    vector<int> a = { 1, 3, 5 };
    vector<int> ans = lexicographicallyLargest(a, n);
    for (auto it : ans)
        cout << it << " ";
    return 0;
}


Java




import java.util.*;
 
public class Main {
 
    public static ArrayList<Integer> lexicographicallyLargest(ArrayList<Integer> a, int n) {
        int i = 0;
        while (i < n) {
            int j = i + 1;
            while (j < n && a.get(j) % 2 == a.get(j - 1) % 2) {
                j++;
            }
            Collections.sort(a.subList(i, j), Collections.reverseOrder());
            i = j;
        }
        return a;
    }
 
    public static void main(String[] args) {
 
        int n = 3;
        ArrayList<Integer> a = new ArrayList<>(Arrays.asList(1, 3, 5));
        ArrayList<Integer> ans = lexicographicallyLargest(a, n);
        for (int it : ans)
            System.out.print(it + " ");
    }
}


Python3




def lexicographicallyLargest(a, n):
    i = 0
    while i < n:
        j = i + 1
        while j < n and a[j] % 2 == a[j - 1] % 2:
            j += 1
        a[i:j] = sorted(a[i:j], reverse=True)
        i = j
    return a
 
# Driver code
n = 3
a = [1, 3, 5]
ans = lexicographicallyLargest(a, n)
for it in ans:
    print(it, end=" ")


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class Program
{
    public static List<int> LexicographicallyLargest(List<int> a, int n)
    {
        int i = 0;
        while (i < n)
        {
            int j = i + 1;
            while (j < n && a[j] % 2 == a[j - 1] % 2)
            {
                j++;
            }
            a.Sort(i, j - i, Comparer<int>.Create((x, y) => y.CompareTo(x)));
            i = j;
        }
        return a;
    }
 
    public static void Main()
    {
        int n = 3;
        List<int> a = new List<int> { 1, 3, 5 };
        List<int> ans = LexicographicallyLargest(a, n);
        foreach (int it in ans)
            Console.Write(it + " ");
    }
}


Javascript




// Sorts the elements in the input array 'a' in a specific way.
function lexicographicallyLargest(a) {
    let i = 0;
    const n = a.length;
     
    while (i < n) {
        let j = i + 1;
         
        // Find a continuous subarray where all elements have the same parity (odd or even).
        while (j < n && a[j] % 2 === a[j - 1] % 2) {
            j++;
        }
         
        // Sort the subarray in descending order to make it lexicographically larger.
        a.slice(i, j).sort((x, y) => y - x);
         
        // Move to the next subarray with different parity (odd or even).
        i = j;
    }
     
    // Return the modified array.
    return a;
}
 
//  Initialize an array 'a' and call the lexicographicallyLargest function.
function main() {
    const a = [1, 3, 5];
    const ans = lexicographicallyLargest(a);
     
    // Print the sorted array.
    for (const it of ans) {
        console.log(it + " ");
    }
}
 
// Calling the main function to execute the code.
main();
 
//Contributed by Aditi Tyagi


Output

5 3 1 

Time Complexity: O(N * logN)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads