Medium
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:
Return the minimum number of operations required to make the array empty, or -1
if it is not possible.
Example 1:
Input: nums = [2,3,3,2,2,4,2,3,4]
Output: 4
Explanation: We can apply the following operations to make the array empty:
It can be shown that we cannot make the array empty in less than 4 operations.
Example 2:
Input: nums = [2,1,2,2,3,3]
Output: -1
Explanation: It is impossible to empty the array.
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 106
import java.util.Arrays;
public class Solution {
public int minOperations(int[] nums) {
Arrays.sort(nums);
int count;
int min = 0;
int current;
int i = 0;
while (i < nums.length) {
current = nums[i];
count = 0;
while (i < nums.length && current == nums[i]) {
count += 1;
i++;
}
if (count == 1) {
return -1;
}
min += (int) Math.ceil(count / (3 * 1.0));
}
return min;
}
}