SHOW:
|
|
- or go back to the newest paste.
| 1 | // Author : Saurav Kalsoor | |
| 2 | - | // Basket Full of Balls - JAVA |
| 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(bucketFullOfBalls(n, k, arr)); |
| 20 | + | System.out.println(beautifulArray(n, k, arr)); |
| 21 | } | |
| 22 | ||
| 23 | - | public static int bucketFullOfBalls(int n, int k, ArrayList<Integer> arr){
|
| 23 | + | public static int beautifulArray(int n, int k, ArrayList<Integer> arr){
|
| 24 | - | HashMap<Integer, Integer> count = new HashMap<>(); |
| 24 | + | HashMap<Integer, Integer> freq = new HashMap<>(); |
| 25 | for(int x : arr){
| |
| 26 | - | count.put(x, count.getOrDefault(x, 0) + 1); |
| 26 | + | freq.put(x, freq.getOrDefault(x, 0) + 1); |
| 27 | } | |
| 28 | ||
| 29 | - | ArrayList<Integer> temp = new ArrayList<>(); |
| 29 | + | Collections.sort(arr); |
| 30 | - | for(Map.Entry<Integer, Integer> m : count.entrySet()){
|
| 30 | + | int res = 0; |
| 31 | - | if(m.getValue() >= k){
|
| 31 | + | |
| 32 | - | temp.add(m.getKey()); |
| 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 | - | int m = temp.size(); |
| 36 | + | |
| 37 | - | if(m == 0){
|
| 37 | + | if(freq.get(arr.get(i)) == 0){
|
| 38 | - | return -1; |
| 38 | + | freq.remove(arr.get(i)); |
| 39 | } | |
| 40 | ||
| 41 | if(freq.containsKey(y)){
| |
| 42 | freq.put(y, freq.get(y) - 1); | |
| 43 | - | int l = temp.get(0), r = l, i = 1; |
| 43 | + | if(freq.get(y) == 0){
|
| 44 | - | while(i < m){
|
| 44 | + | freq.remove(y); |
| 45 | - | int j = i - 1; |
| 45 | + | } |
| 46 | - | while(i < m && temp.get(i) == temp.get(i-1) + 1){
|
| 46 | + | }else{
|
| 47 | - | i++; |
| 47 | + | res++; |
| 48 | } | |
| 49 | - | i--; |
| 49 | + | |
| 50 | } | |
| 51 | - | if(temp.get(i) - temp.get(j) > r - l){
|
| 51 | + | return res; |
| 52 | - | l = temp.get(j); |
| 52 | + | |
| 53 | - | r = temp.get(i); |
| 53 | + | |
| 54 | } | |
| 55 | ||
| 56 | - | i+=2; |
| 56 | + |