![]() |
VOOZH | about |
Given an array arr[] of size n, the task is to find the lexicographically largest permutation by sequentially inserting the array elements to the front or the back of another array which is to be considered initially empty.
Examples:
Input: arr[] = [3, 1, 2, 4]
Output: 4 3 1 2
Explanation:
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 lexicographically largest permutation.Input: arr[] = [1, 2, 3, 4, 5]
Output: 5 4 3 2 1
Approach:
The given problem can be solved by using the Greedy Approach using the deque. The idea is to simply insert the first element into an empty deque, then for the remaining elements, always put the larger element to the front and smaller element to the rear.
Step by step approach:
4 3 1 2
Time Complexity: O(n)
Auxiliary Space: O(n)