Advertisement
saurav_kalsoor

Beautiful Array- JAVA

Aug 12th, 2022
987
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Author : Saurav Kalsoor
  2. // Beautiful Array - JAVA
  3.  
  4.  
  5. import java.util.*;
  6.  
  7. public class Test {
  8.    
  9.     static Scanner sc = new Scanner(System.in);
  10.  
  11.     public static void main(String[] args) {
  12.         int n = sc.nextInt();
  13.         int k = sc.nextInt();
  14.  
  15.         ArrayList<Integer> arr = new ArrayList<>();
  16.         for(int i=0; i < n ;i++){
  17.             arr.add(sc.nextInt());
  18.         }
  19.  
  20.         System.out.println(beautifulArray(n, k, arr));
  21.     }
  22.  
  23.     public static int beautifulArray(int n, int k, ArrayList<Integer> arr){
  24.         HashMap<Integer, Integer> freq = new HashMap<>();
  25.         for(int x : arr){
  26.             freq.put(x, freq.getOrDefault(x, 0) + 1);
  27.         }
  28.  
  29.         Collections.sort(arr);
  30.         int res = 0;
  31.        
  32.         for(int i = 0; i < n; i++){
  33.             if(freq.containsKey(arr.get(i))){
  34.                 int y = k * arr.get(i);
  35.                 freq.put(arr.get(i), freq.get(arr.get(i)) - 1);
  36.  
  37.                 if(freq.get(arr.get(i)) == 0){
  38.                     freq.remove(arr.get(i));
  39.                 }
  40.  
  41.                 if(freq.containsKey(y)){
  42.                     freq.put(y, freq.get(y) - 1);
  43.                     if(freq.get(y) == 0){
  44.                         freq.remove(y);
  45.                     }
  46.                 }else{
  47.                     res++;
  48.                 }
  49.             }
  50.         }
  51.         return res;
  52.     }
  53.    
  54. }
  55.  
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement