Skip to content

Commit 5befd97

Browse files
committedApr 2, 2025
Add solution #1053
1 parent 424aaea commit 5befd97

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,122 LeetCode solutions in JavaScript
1+
# 1,123 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -858,6 +858,7 @@
858858
1049|[Last Stone Weight II](./solutions/1049-last-stone-weight-ii.js)|Medium|
859859
1051|[Height Checker](./solutions/1051-height-checker.js)|Easy|
860860
1052|[Grumpy Bookstore Owner](./solutions/1052-grumpy-bookstore-owner.js)|Medium|
861+
1053|[Previous Permutation With One Swap](./solutions/1053-previous-permutation-with-one-swap.js)|Medium|
861862
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
862863
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
863864
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 1053. Previous Permutation With One Swap
3+
* https://leetcode.com/problems/previous-permutation-with-one-swap/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of positive integers arr (not necessarily distinct), return the lexicographically
7+
* largest permutation that is smaller than arr, that can be made with exactly one swap. If it
8+
* cannot be done, then return the same array.
9+
*
10+
* Note that a swap exchanges the positions of two numbers arr[i] and arr[j]
11+
*/
12+
13+
/**
14+
* @param {number[]} arr
15+
* @return {number[]}
16+
*/
17+
var prevPermOpt1 = function(arr) {
18+
const result = [...arr];
19+
let swapIndex = -1;
20+
21+
for (let i = arr.length - 2; i >= 0; i--) {
22+
if (arr[i] > arr[i + 1]) {
23+
swapIndex = i;
24+
break;
25+
}
26+
}
27+
28+
if (swapIndex === -1) return arr;
29+
30+
let maxLessIndex = swapIndex + 1;
31+
for (let j = swapIndex + 2; j < arr.length; j++) {
32+
if (arr[j] < arr[swapIndex] && arr[j] > arr[maxLessIndex]) {
33+
maxLessIndex = j;
34+
}
35+
}
36+
37+
[result[swapIndex], result[maxLessIndex]] = [result[maxLessIndex], result[swapIndex]];
38+
39+
return result;
40+
};

0 commit comments

Comments
 (0)
Please sign in to comment.