fork download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. class Main {
  5. public static int minOperationsToDestroyArray(int[] arr) {
  6. Map<Integer, Integer> freqMap = new HashMap<>();
  7. for (int num : arr){
  8. freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
  9. }
  10.  
  11. int minOperations = 0;
  12. for ( Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
  13. int freq = entry.getValue();
  14. if (freq == 1) {
  15. return -1;
  16. } else {
  17. //we can consume 2 or 3 elements in one operation
  18. // for min .. see how many 3's can be removed
  19. // remainder can be 1 or 2 or 0 if 0 no extra operation
  20. // if remainder is 1 it means that it can be coupled with a 3 to form 4 thats 2 + 2 .. thats 2 operations now
  21. // remainder 2 then add 1 or if 1 then also add 1 .. thats the meaning of freq % 3 != 0 ? 1 : 0
  22.  
  23. minOperations += freq / 3 + (freq % 3 != 0 ? 1 : 0);
  24. }
  25. }
  26. return minOperations;
  27. }
  28.  
  29. public static void main(String[] args) {
  30. int[] arr = {1, 5, 5, 1, 1, 8, 8, 10, 10};
  31. int minOps = minOperationsToDestroyArray(arr);
  32. if (minOps == -1) {
  33. System.out.println("it's not possible to destroy the array.");
  34. } else {
  35. System.out.println("Minimum number of operations to destroy the array: " + minOps);
  36. }
  37. }
  38. }
  39.  
Success #stdin #stdout 0.12s 55580KB
stdin
Standard input is empty
stdout
Minimum number of operations to destroy the array: 4