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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int MinOperations(int[] nums) {
6 Dictionary<int, int> freq = new Dictionary<int, int>();
7 foreach (var num in nums) {
8 if (!freq.ContainsKey(num)) {
9 freq[num] = 0;
10 }
11 freq[num]++;
12 }
13 int operations = 0;
14 foreach (var kvp in freq) {
15 int count = kvp.Value;
16 if (count == 1) return -1;
17 operations += (count + 2) / 3;
18 }
19 return operations;
20 }
21}
A Dictionary
is used to count frequencies. Post frequency calculation, we iterate over the values to determine the operations needed. By computing (count + 2) / 3
, we effectively perform a ceiling operation to find how many triple removals are necessary for each number.
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.