[LeetCode] Previous Permutation With One Swap

1053. Previous Permutation With One Swap

Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<int> prevPermOpt1(vector<int>& A) {
int n = A.size(), p = n - 1;
for(int i = n - 1; i > 0; i--) {
if(A[i] < A[i - 1]) {
p = i - 1;
break;
}
}
if(p == n - 1) return A;

int p2 = p + 1 == n ? p : p + 1;
for(int i = p + 1; i < n; i++) {
if(A[i] < A[p]) {
if(A[i] > A[p2])
p2 = i;
}
}
swap(A[p2], A[p]);
return A;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/20/PS/LeetCode/previous-permutation-with-one-swap/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.