- Arrays, deque, Greedy, lexicographic-ordering, Mathematical, permutation

Lexicographically largest permutation by sequentially inserting Array elements at ends

Given an array arr[] of N integers, the task is to find the lexicographically largest permutation by sequentially inserting the array elements to the front or the back of another array.Examples:Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.Input: arr[] = {3, 1, 2, 4}Output: 4 3 1 2Explanation:The permutations that can be created by sequentially inserting the array elements to the front or the back of the container are {3, 1, 2, 4}, {1, 3, 2, 4}, {2, 3, 1, 4}, {2, 1, 3, 4}, {4, 1, 3, 2}, {4, 2, 3, 1}, {4, 2, 1, 3}, and {4, 3, 1, 2}. Out of which {4, 3, 1, 2} is the lexographically largest permutation.Input: arr[] = {1, 2, 3, 4, 5}Output: 5 4 3 2 1Approach: The given problem can be solved by using the Greedy Approach using the deque which is based on the observation that if the current array element is at least the first element of the new array, the most optimal choice always is to insert that element in front of the container in order to lexicographically maximize the permutation. Otherwise, insert the element to the end of the array. Follow the steps below to solve the given problem:Initialize a deque, say DQ, which stores the current state of the container.Initialize a variable, say mx, which stores the maximum till each index representing the 1stelement of the deque DQ.Traverse the given array arr[] and if the current element arr[i] >= mx, then insert arr[i] to the front of the deque DQ and update the value of mx. Otherwise, insert arr[i] to the back of the deque DQ.After completing the above steps, print the elements stored in the deque DQ as the resultant largest permutation.Below is the implementation of the above approach:C++  #include using namespace std;  void largestPermutation(int arr[], int N){              deque p;              int mx = arr[0];    p.push_back(arr[0]);          for (int i = 1; i < N; i++) {                                  if (arr[i] < mx)            p.push_back(arr[i]);                          else {            p.push_front(arr[i]);                                      mx = arr[i];        }    }          for (auto i : p)        cout