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.
1from collections import Counter
2
3def min_operations(nums):
4 freq = Counter(nums)
5 operations = 0
6 for count in freq.values():
7 if count == 1:
8 return -1
9 op = count // 3
10 if count % 3 != 0:
11 op += 1
12 operations += op
13 return operations
We first use Counter
from collections
to get the frequency of each number in the array. Then, for each frequency, we calculate how many pairs or triples can be removed. We need at least pairs to remove numbers, so if a number appears only once in the list, we return -1. Otherwise, we take the integer division by 3 to count the full groups of 3 elements and add one more operation if there's a remainder. This approach results in efficient calculations to find the minimum operations.
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.
1import
This Java version follows a greedy pattern where frequency counts are adjusted using pair and triplet removals to achieve minimal operations by prioritizing larger removals with triplets first, pairs only when fitting in end cases.