Input: nums =[2,3,3,2,2,4,2,3,4]Output: 4Explanation: We can apply the following operations to make the array empty:- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums =[3,3,2,4,2,3,4].- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums =[3,3,4,3,4].- Apply the second operation on the elements at indices 0,1, and 3. The resulting array is nums =[4,4].- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums =[].It can be shown that we cannot make the array empty in less than 4 operations.
For each value, we can only remove 2 or 3 at a time. If a value appears once, it’s impossible. Otherwise, we use as many 3-removals as possible, and the rest as 2-removals.
import java.util.*;
classSolution {
publicintminOperations(int[] nums) {
Map<Integer, Integer> freq =new HashMap<>();
for (int n : nums) freq.put(n, freq.getOrDefault(n, 0) + 1);
int ans = 0;
for (int f : freq.values()) {
if (f == 1) return-1;
ans += (f + 2) / 3;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funminOperations(nums: IntArray): Int {
val freq = mutableMapOf<Int, Int>()
for (n in nums) freq[n] = freq.getOrDefault(n, 0) + 1var ans = 0for (f in freq.values) {
if (f ==1) return -1 ans += (f + 2) / 3 }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
from collections import Counter
classSolution:
defminOperations(self, nums: list[int]) -> int:
freq = Counter(nums)
ans =0for f in freq.values():
if f ==1:
return-1 ans += (f +2) //3return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::collections::HashMap;
impl Solution {
pubfnmin_operations(nums: Vec<i32>) -> i32 {
letmut freq = HashMap::new();
for n in nums { *freq.entry(n).or_insert(0) +=1; }
letmut ans =0;
for&f in freq.values() {
if f ==1 { return-1; }
ans += (f +2) /3;
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
minOperations(nums: number[]):number {
constfreq=newMap<number, number>();
for (constnofnums) freq.set(n, (freq.get(n) ??0) +1);
letans=0;
for (constfoffreq.values()) {
if (f===1) return-1;
ans+= Math.floor((f+2) /3);
}
returnans;
}
}