[LeetCode] Minimum Number of Operations to Make Array Empty

2870. Minimum Number of Operations to Make Array Empty

You are given a 0-indexed array nums consisting of positive integers.

There are two types of operations that you can apply on the array any number of times:

  • Choose two elements with equal values and delete them from the array.
  • Choose three elements with equal values and delete them from the array.

Return the minimum number of operations required to make the array empty, or -1 if it is not possible.

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 {
long long helper(int x) {
if(x == 0) return 0;
if(x == 2) return 1;
if(x == 3) return 1;
if(x == 1) return INT_MAX;
return min(helper(x - 2), helper(x - 3)) + 1;
}
long long best(int x) {
if(x == 2) return 1;
if(x == 3) return 1;
if(x <= 6) return helper(x);
int rem = x % 6 + 6;
int res = (x - rem) / 3;
return res + helper(rem);
}
public:
int minOperations(vector<int>& nums) {
unordered_map<int,int> mp;
for(auto n : nums) mp[n] += 1;
int res = 0;
for(auto& [k,v] : mp) {
if(v == 1) return -1;
res += best(v);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/01/PS/LeetCode/minimum-number-of-operations-to-make-array-empty/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.