class Solution {
public int[] numMovesStonesII(int[] stones) {
Arrays.sort(stones);
return new int[]{findMin(stones), findMax(stones)};
}
int findMin(int[] stones){
int n = stones.length;
int j = 0;
int min = n;
for(int i = 0; i < n; ++i){
while(stones[i] - stones[j] + 1 > n)
j++;
int count = i - j + 1;
if(count == n - 1 && stones[i] - stones[j] == n - 2){
min = Math.min(min, 2);
}else{
int gapcount = n - count;
min = Math.min(min, gapcount);
}
}
return min;
}
int findMax(int[] stones){
int sum = 0;
for(int i = 1; i < stones.length; ++i){
sum += stones[i] - stones[i - 1] - 1;
}
int n = stones.length;
if(n >= 1 && stones[1] != stones[0] + 1){
if(n >= 2 && stones[n - 1] != stones[n - 2] + 1){
int gap1 = stones[1] - stones[0] - 1;
int gap2 = stones[n - 1] - stones[n - 2] - 1;
return sum - Math.min(gap1, gap2);
}
}
return sum;
}
}