![]() |
VOOZH | about |
Given an arr[] of size n, the task is to find the lexicographically largest permutation from the given permutation by performing the following operations exactly once where you will choose two integers l and r and reverse the subarray [l, r] and swap [1, l-1] with [r+1, n].
Examples:
Input: arr[] = { 2, 3, 1, 5, 4}
Output: {5, 4, 1, 3, 2 }
Explanation: we will choose l = 2 and r =3, then after performing operation, the permutation will be {5, 4, 3, 1, 2 }Input: arr[] = { 6, 1, 2, 3, 5, 4 }
Output: {5, 4, 3, 6, 1, 2 }
Explanation: we will choose l = 4 and r = 4, then after performing the operation, the permutation will be {5, 4, 3, 6, 1, 2}
Approach: To solve the problem follow the below idea:
There will be two cases:
- If arr[0] = n . if arr[1] == n-1, then choose l = 0 and r = 0. Else let arr[j] = n-1, then choose l = j-1 and r = j-19(0-based indexing ) .
- If arr[0] != n . let arr[j] = n, then iterate while loop from j-1 to 0 till arr[i] > arr[0] and decrease i by 1, then our l will be i and r will be j.
Below is the implementation of the above approach:
5 4 1 3 2
Time Complexity: O(N)
Auxiliary Space: O(N)