[LeetCode] Moving Stones Until Consecutive II

1040. Moving Stones Until Consecutive II

There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones.

Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.

  • In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone.

The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).

Return an integer array answer of length 2 where:

  • answer[0] is the minimum number of moves you can play, and
  • answer[1] is the maximum number of moves you can play.
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
class Solution {
int mi(vector<int> A) {
int res = INT_MAX, l = 0, r = 0, n = A.size();
while(r < n) {
while(r < n and A[r] < A[l] + n){
if(r - l + 1 == n - 1 and A[r] - A[l] == n - 2) res = min(res,2);
else res = min(res, n - (r - l + 1));
r++;
}
l++;
}
return res;
}
int ma(vector<int> A) {
int res = 0;
int res2 = 0;
for(int i = 1, j = A.size() - 2; i < A.size()-1; i++,j--) {
res += A[i + 1] - A[i] - 1;
res2 += A[j] - A[j-1] - 1;
}
return max(res,res2);
}
public:
vector<int> numMovesStonesII(vector<int>& A) {
sort(begin(A), end(A));
return {mi(A), ma(A)};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/13/PS/LeetCode/moving-stones-until-consecutive-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.