-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1053-previous-permutation-with-one-swap.js
More file actions
40 lines (34 loc) · 1.04 KB
/
1053-previous-permutation-with-one-swap.js
File metadata and controls
40 lines (34 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 1053. Previous Permutation With One Swap
* https://leetcode.com/problems/previous-permutation-with-one-swap/
* Difficulty: Medium
*
* 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. If it
* cannot be done, then return the same array.
*
* Note that a swap exchanges the positions of two numbers arr[i] and arr[j]
*/
/**
* @param {number[]} arr
* @return {number[]}
*/
var prevPermOpt1 = function(arr) {
const result = [...arr];
let swapIndex = -1;
for (let i = arr.length - 2; i >= 0; i--) {
if (arr[i] > arr[i + 1]) {
swapIndex = i;
break;
}
}
if (swapIndex === -1) return arr;
let maxLessIndex = swapIndex + 1;
for (let j = swapIndex + 2; j < arr.length; j++) {
if (arr[j] < arr[swapIndex] && arr[j] > arr[maxLessIndex]) {
maxLessIndex = j;
}
}
[result[swapIndex], result[maxLessIndex]] = [result[maxLessIndex], result[swapIndex]];
return result;
};