Moving Stones Until Consecutive II LeetCode solution in C++

1
class Solution {
2
public:
3
vector<int> numMovesStonesII(vector<int> &stones) {
4
sort(stones.begin(), stones.end());
5
int n = stones.size();
6
int MAX = 0;
7
int MIN = INT_MAX;
8
int a = stones.back() - stones[1] + 1 - (n - 1);
9
int b = stones[n - 2] - stones[0] + 1 - (n - 1);
10
int j = 0;
11
MAX = max(a, b);
12
for (int i = 0; i < n; i++) {
13
while (j < n && stones[j] - stones[i] + 1 < n) {
14
j++;
15
}
16
if (j >= n) {
17
break;
18
}
19
int gap;
20
if (stones[j] - stones[i] + 1 == n) {
21
gap = n - (j - i + 1);
22
} else if (j - 1 - i + 1 == n - 1) {
23
gap = 2;
24
} else {
25
gap = n - (j - 1 - i + 1);
26
}
27
MIN = min(MIN, gap);
28
}
29
return {MIN, MAX};
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0