[LeetCode] Minimum Adjacent Swaps to Make a Valid Array

2340. Minimum Adjacent Swaps to Make a Valid Array

You are given a 0-indexed integer array nums.

Swaps of adjacent elements are able to be performed on nums.

A valid array meets the following conditions:

  • The largest element (any of the largest elements if there are multiple) is at the rightmost position in the array.
  • The smallest element (any of the smallest elements if there are multiple) is at the leftmost position in the array.

Return the minimum swaps required to make nums a valid array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int minimumSwaps(vector<int>& A) {
int mi = INT_MAX, mip = -1, ma = INT_MIN, map = -1, n = A.size(), res = 0;
for(int i = 0; i < n; i++) {
if(mi > A[i]) {
mi = A[i];
mip = i;
}
}
res += mip;
while(mip) {
swap(A[mip], A[--mip]);
}
for(int i = 0; i < n; i++) {
if(ma <= A[i]) {
ma = A[i];
map = i;
}
}
res += (n - map - 1);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/18/PS/LeetCode/minimum-adjacent-swaps-to-make-a-valid-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.