[LeetCode] Minimum Number of Operations to Make Array Continuous

2009. Minimum Number of Operations to Make Array Continuous

You are given an integer array nums. In one operation, you can replace any element in nums with any integer.

nums is considered continuous if both of the following conditions are fulfilled:

  • All elements in nums are unique.
  • The difference between the maximum element and the minimum element in nums equals nums.length - 1.

For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.

Return the minimum number of operations to make nums continuous.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#define all(a) begin(a), end(a)
class Solution {
public:
int minOperations(vector<int>& A) {
int n = A.size(), l = 0, r = 0, res = INT_MAX, dup = 0;
sort(all(A));
while(r + 1 < n and A[r + 1] <= A[l] + n - 1) {
if(A[r] == A[r+1]) dup++;
r++;
}

while(l < n) {
res = min(res,dup + l + n - r - 1);
if(l + 1 < n and A[l + 1] == A[l]) dup--;
l++;
while(r + 1 < n and A[r + 1] <= A[l] + n - 1) {
if(A[r] == A[r+1]) dup++;
r++;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/26/PS/LeetCode/minimum-number-of-operations-to-make-array-continuous/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.