Sponsored
Sponsored
This approach leverages the frequency count of each number to determine the minimum number of operations needed. We will iterate over the frequency list and for each number, calculate the possible number of operations (either removing two or three elements at a time).
Time Complexity: O(n), where n is the length of the array, as we are iterating through the array and frequencies. Space Complexity: O(n) for storing the frequency count.
1#include <vector>
2#include <unordered_map>
3#include <cmath>
4
5int minOperations(std::vector<int>& nums) {
6 std::unordered_map<int, int> freq;
7 for (int num : nums) {
8 freq[num]++;
9 }
10 int operations = 0;
11 for (auto it : freq) {
12 int count = it.second;
13 if (count == 1) return -1;
14 operations += std::ceil((double)count / 3);
15 }
16 return operations;
17}
We use an unordered_map
to store the frequency of each element. For each element's frequency, if it is 1, we return -1 because that's insufficient for a pair or triple removal. We use ceil
to find the number of times we need to perform triple operations, adding one more operation if there is a remainder. This solution is efficient as it leverages hash tables to maintain frequency counts.
This approach targets optimizing operations by prioritizing pair removals wherever possible, then triples. The main idea is to use as many pair removals as possible, and only use triples to fill gaps that pairs cannot cover fully.
Time Complexity: O(n), both for listing and iterating through frequencies. Space Complexity: O(n) for the frequency map.
1from collections
Using Counter
for frequency counts, we iterate through controlling operations greedily by continuously subtracting 3 (for triples) unless only a single pair remains. This logic ensures minimal operations by prioritizing large removals over small ones unless strictly necessary.