Suppose we have an array A of positive integers (not necessarily unique), we have to find the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]). If it cannot possible, then return the same array. So if the array is like [3,2,1], then the output will be [3,1,2], by swapping 2 and 1
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def prevPermOpt1(self, A): n = len(A) for left in range(n-2,-2,-1): if left == -1: return A elif A[left]>A[left+1]: break element = 0 index = 0 for right in range(left+1,n): if A[right]<A[left] and A[right]>element: element = A[right] index = right temp = A[left] A[left] = A[index] A[index] = temp return A ob = Solution() print(ob.prevPermOpt1([4,2,3,1,3]))
[4,2,3,1,3]
[4, 2, 1, 3, 3]