[LeetCode] Minimum Deletions to Make Array Beautiful

2216. Minimum Deletions to Make Array Beautiful

You are given a 0-indexed integer array nums. The array nums is beautiful if:

  • nums.length is even.
  • nums[i] != nums[i + 1] for all i % 2 == 0.

Note that an empty array is considered beautiful.

You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.

Return the minimum number of elements to delete from nums to make it beautiful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int minDeletion(vector<int>& A) {
int res = 0, n = A.size();
for(int i = 0; i < n;) {
if(i + 1 == n) break;
if(A[i] == A[i + 1]) {
int j = i + 1;
while(j < n and A[j] == A[i]) j++;
res += j - i - 1;
i = j + 1;
} else i += 2;
}
if((n - res) & 1) res += 1;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/05/PS/LeetCode/minimum-deletions-to-make-array-beautiful/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.